Convert DateTimeOffset to Python date

196 Views Asked by At

I am trying to convert a DateTimeOffset with the format 2022-08-13T06:18:56.1890000+00:00, using the isoformat, but I'm getting the error:

"Invalid isoformat string: '2022-08-13T06:18:56.1890000+00:00'

datetime.fromisoformat('2022-08-13T06:18:56.1890000+00:00')
1

There are 1 best solutions below

0
FObersteiner On

Python < 3.11: you can use a third-party library such as dateutil or iso8601:

from dateutil import parser # pip install python-dateutil
s = "2022-08-13T06:18:56.1890000+00:00"
print(parser.isoparse(s))
# 2022-08-13 06:18:56.189000+00:00

Python >= 3.11: use fromisoformat, ex:

from datetime import datetime
s = "2022-08-13T06:18:56.1890000+00:00"
print(datetime.fromisoformat(s))
# 2022-08-13 06:18:56.189000+00:00

# just the date:
print(datetime.fromisoformat(s).date())
# 2022-08-13