Python format a string date to actual format gives me error

Question:

Trying to update the startdate resulted in an error.

Code:

startdate = '2022-12-20 10:18:00+00:00'
date_format_str = "%Y-%d-%m %H:%M:%S%z"
starttime = datetime.strptime(startdate, date_format_str)

Error:

ValueError: time data '2022-12-20 10:18:00+00:00' does not match format '%Y-%d-%m %H:%M:%S%z'
Asked By: amolc

||

Answers:

You mixed up the day and month format codes, as @John Gordon notes. Fortunately, the format of your variable startdate is exactly the specific ISO-8601 compliant format that datetime.fromisoformat() can parse, so you didn’t need to bother:

In [1]: from datetime import datetime

In [2]: startdate = "2022-12-20 10:18:00+00:00"

In [3]: datetime.fromisoformat(startdate)
Out[3]: datetime.datetime(2022, 12, 20, 10, 18, tzinfo=datetime.timezone.utc)
Answered By: ddejohn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.