Python 3.11 update
This is now handled correctly by the ISO format parser. Ex:
Python 3.11.4 (main, Jun 27 2023, 19:27:25) [GCC 13.1.1 20230614 (Red Hat 13.1.1-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> s = "2020-07-30T20:40:33.1000000Z"
>>> dt = datetime.fromisoformat(s)
>>> print(dt)
2020-07-30 20:40:33.100000+00:00
Old answer
If you really have 7 decimal places of fractional seconds and don't care about the 1/10th of the microseconds, you could use a re.sub
and datetime.fromisoformat
:
import re
from datetime import datetime
s = "2020-07-30T20:40:33.1000000Z"
dt = datetime.fromisoformat(re.sub('[0-9]Z', '+00:00', s))
print(dt)
print(repr(dt))
2020-07-30 20:40:33.100000+00:00
datetime.datetime(2020, 7, 30, 20, 40, 33, 100000, tzinfo=datetime.timezone.utc)
...or use dateutil
's parser:
from dateutil import parser
dt = parser.parse(s)
print(dt)
print(repr(dt))
2020-07-30 20:40:33.100000+00:00
datetime.datetime(2020, 7, 30, 20, 40, 33, 100000, tzinfo=tzutc())
...or even pandas
's to_datetime, if you maybe work with that lib anyway:
import pandas as pd
dt = pd.to_datetime(s)
print(dt)
print(repr(dt))
2020-07-30 20:40:33.100000+00:00
Timestamp('2020-07-30 20:40:33.100000+0000', tz='UTC')
often irrelevant (depending on use-case) but note that convenience costs you some more time:
%timeit datetime.fromisoformat(re.sub('[0-9]Z', '+00:00', s))
1.92 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit parser.parse(s)
79.8 µs ± 3.46 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit pd.to_datetime(s)
62.4 µs ± 1.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)