Skip to content

Instantly share code, notes, and snippets.

@moreati
Created April 8, 2024 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moreati/85de3f0745d473f54dd9076125338642 to your computer and use it in GitHub Desktop.
Save moreati/85de3f0745d473f54dd9076125338642 to your computer and use it in GitHub Desktop.
Python 3.11 datetime.datetime.fromisoformat()

In Python 3.11+ datetime.datetime.fromisoformat() accepts any number of decimal places for the seconds component. If there are more than 6 then the resulting datetime object is truncated (not rounded) to microsecond precision.

Python 3.11.8 (main, Feb  6 2024, 21:21:21) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin
>>> import datetime
>>> datetime.datetime.fromisoformat('2011-11-04T00:05:23.12345Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, 123450, tzinfo=datetime.timezone.utc)
>>> datetime.datetime.fromisoformat('2011-11-04T00:05:23.1234567Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, 123456, tzinfo=datetime.timezone.utc)

In Python 3.10 and before it only accepts exactly 6 decimal places (or no decimal point).

Python 3.10.14 (main, Mar 19 2024, 21:46:16) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
>>> import datetime
>>> datetime.datetime.fromisoformat('2011-11-04T00:05:23.12345Z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: '2011-11-04T00:05:23.12345Z'
>>> datetime.datetime.fromisoformat('2011-11-04T00:05:23.1234567Z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: '2011-11-04T00:05:23.1234567Z'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment