52

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
  • 115,751
  • 26
  • 228
  • 437
stephendwolff
  • 1,382
  • 1
  • 13
  • 27
  • 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
  • 36
    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

5 Answers5

33

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
  • 115,751
  • 26
  • 228
  • 437
stephendwolff
  • 1,382
  • 1
  • 13
  • 27
24

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
  • 687
  • 5
  • 12
6

Proper ISO format including the timezone is now supported in 3.11

https://docs.python.org/3.11/library/datetime.html#datetime.datetime.fromisoformat

regoawt
  • 106
  • 1
  • 2
1

I had the same issue and solve it based in this answer.

from dateutil import parser
yourdate = parser.parse(datestring)

It returns a datetime.datetime so is perfect.

J Agustin Barrachina
  • 3,501
  • 1
  • 32
  • 52
-15

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
  • 1,095
  • 1
  • 9
  • 8