2

In Python 3.10.8, if I write

from datetime import datetime
print(datetime.fromisoformat('2011-11-04T00:05:23Z'))

I get the error

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(datetime.fromisoformat('2011-11-04T00:05:23Z'))
ValueError: Invalid isoformat string: '2011-11-04T00:05:23Z'

This is surprising, since this example is taken directly out of the datetime module documentation:

>>> from datetime import datetime
# ...
>>> datetime.fromisoformat('2011-11-04T00:05:23Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)

Is this a bug or an error in the documentation?

Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76

2 Answers2

4

Prior to Python 3.11, fromisoformat required the same format as isoformat.

Python isoformat did not support a trailing Z as an alias for +00:00, hence the error.

From the 3.10 docs:

Caution - This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat() https://docs.python.org/3.10/library/datetime.html#datetime.datetime.fromisoformat

From the >=3.11 docs:

Changed in version 3.11: Previously, this method only supported formats that could be emitted by date.isoformat() or datetime.isoformat(): https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

match
  • 10,388
  • 3
  • 23
  • 41
  • 1
    _"Python isoformat does not contain Timezone information"_ seems misleading. Something like `datetime.fromisoformat('2011-11-04T00:05:23.234+04:00')` and `datetime(..., tzinfo=timezone.utc).isoformat()` were perfectly valid. It's just that using `Z` as an alias for `+00:00` wasn't supported. – Brian61354270 Mar 28 '23 at 14:40
  • Have clarified regarding the trailing Z. – match Mar 29 '23 at 13:58
0

The example

>>> from datetime import datetime
>>> datetime.fromisoformat('2011-11-04T00:05:23Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)

in the datetime docs is only present in Python 3.11+. It's missing in Python 3.10.

The ability for datetime.isoformat to parse a trailing Z suffix as an alias for +00:00 was introduced in BPO 35829 / BPO 46614 for Python 3.11.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43