I need to parse RFC 3339 strings like \"2008-09-03T20:56:35.450686Z\"
into Python\'s datetime
type.
I have found strptime in the Python sta
A simple option from one of the comments: replace 'Z'
with '+00:00'
- and use Python3.7+'s fromisoformat
.
from datetime import datetime
s = "2008-09-03T20:56:35.450686Z"
datetime.fromisoformat(s.replace('Z', '+00:00'))
# datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=datetime.timezone.utc)
Although strptime
can parse the 'Z'
character, fromisoformat
is faster by ~ x40 (see also: A faster strptime):
%timeit datetime.fromisoformat(s.replace('Z', '+00:00'))
387 ns ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')
15.3 µs ± 540 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)