26

I supply "2019-04-05T16:55:26Z" to Python 3's datetime.datetime.fromisoformat and get Invalid isoformat string, though the same string works without the Z. ISO8601 allows for the Z - https://en.wikipedia.org/wiki/ISO_8601

$ python3
Python 3.7.2 (default, Feb 12 2019, 08:15:36)

>>> datetime.fromisoformat("2019-04-05T16:55:26Z")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: '2019-04-05T16:55:26Z'

>>> datetime.fromisoformat("2019-04-05T16:55:26")
datetime.datetime(2019, 4, 5, 16, 55, 26)
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
stephendwolff
  • 947
  • 1
  • 9
  • 25
  • 1
    Possible duplicate https://stackoverflow.com/questions/19654578/python-utc-datetime-objects-iso-format-doesnt-include-z-zulu-or-zero-offset – Nick Vitha Apr 05 '19 at 19:39
  • [The docs](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) clearly state what's supported. – jonrsharpe Apr 05 '19 at 19:40
  • 20
    Yes they do, but perhaps the name is misleading given that they don't work with the actual ISO format! – stephendwolff Apr 06 '19 at 20:04

3 Answers3

21

I just checked the Python 3 documentation and it isn't intended to parse arbitrary ISO8601 format strings:

Caution: This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat().

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
stephendwolff
  • 947
  • 1
  • 9
  • 25
5

If you already know the format your API responds, you can use:

from datetime import datetime
datetime.strptime("2022-04-07T08:53:42.06717+02:00", "%Y-%m-%dT%H:%M:%S.%f%z")

Adjust for your needs, if the string for example does not contain milliseconds, etc.

Otherwise, as the official python documentation suggests, use the dateutil package: https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse

NicoHood
  • 136
  • 1
  • 6
-8

It is so simple. Just remove the last letter Z.

>>> from datetime import datetime; datetime.fromisoformat("2019-04-05T16:55:26")
datetime.datetime(2019, 4, 5, 16, 55, 26)
dom free
  • 893
  • 1
  • 8
  • 8