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 standard library, but it is not very convenient.
What is the best way to do this?
28 s
The datetime
standard library has, since Python 3.7, a function for inverting datetime.isoformat()
.
classmethod
datetime.fromisoformat(date_string)
:Return a
datetime
corresponding to adate_string
in one of the formats emitted bydate.isoformat()
anddatetime.isoformat()
.Specifically, this function supports strings in the format(s):
YYYY-MM-DD[*HH[:MM[:SS[.mmm[mmm]]]][+HH:MM[:SS[.ffffff]]]]
where
*
can match any single character.Caution: This does not support parsing arbitrary ISO 860Best Answertrings – it is only intended as the inverse operation of
datetime.isoformat()
.Examples:
>>> from datetime import datetime >>> datetime.fromisoformat('2011-11-04') datetime.datetime(2011, 11, 4, 0, 0)
…
Be sure to read the caution from the docs!