0

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')
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Try [link](https://stackoverflow.com/questions/55542280/why-does-python-3-find-this-iso8601-date-2019-04-05t165526z-invalid), fromisoformat just operates as the inverse of isoformat(), but does not parse your string. You will get the entire answer and possible solutions. – Aleix Molla Jun 27 '23 at 17:06
  • 1
    @AleixMolla that is only true for Python versions before 3.11. The ISO format parser has been extended in Python 3.11. The problem here are 7 digits of fractional seconds. The "new" parser can handle it, the old one can't. – FObersteiner Jun 27 '23 at 17:20
  • @FObersteiner Thank you, didn't know that change. I tried `datetime.fromisoformat('2022-08-13T06:18:57.890000+00:00')` and it worked, as the max range from microseconds is 1,000,000. – Aleix Molla Jun 27 '23 at 17:28
  • answered a [related question](https://stackoverflow.com/q/63447615/10197418) some time ago - extended by the Python 3.11 option now. – FObersteiner Jun 27 '23 at 17:30
  • 1
    @AleixMolla yes, since vanilla Python's datetime data structure only has a precision of microseconds (1e-6 s), any additional digits (> 6) of fractional seconds are basically ignored. – FObersteiner Jun 27 '23 at 17:34

1 Answers1

0

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72