'Date format for year/month/date'T'/hour/minute/second/timezone in Python

In Python I would like to turn my str to time object and I am receiving an error.

ValueError: time data '2022-04-13T09:52:49-04:00' does not match format 

What format should I use here? Thanks



Solution 1:[1]

Try:

>>> datetime.strptime('2022-04-13T09:52:49-04:00',"%Y-%m-%dT%H:%M:%S%z")
datetime.datetime(2022, 4, 13, 9, 52, 49, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

Solution 2:[2]

ISO 8601 format was used, so it is task for datetime.datetime.fromisoformat

import datetime
d = '2022-04-13T09:52:49-04:00'
dt = datetime.datetime.fromisoformat(d)
print(repr(dt))

output

datetime.datetime(2022, 4, 13, 9, 52, 49, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 not_speshal
Solution 2 Daweo