How do I parse an ISO 8601-formatted date? How do I parse an ISO 8601-formatted date? python python

How do I parse an ISO 8601-formatted date?


isoparse function from python-dateutil

The python-dateutil package has dateutil.parser.isoparse to parse not only RFC 3339 datetime strings like the one in the question, but also other ISO 8601 date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date).

>>> import dateutil.parser>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 formatdatetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended formatdatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)>>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic formatdatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)>>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date onlydatetime.datetime(2008, 9, 3, 0, 0)

The python-dateutil package also has dateutil.parser.parse. Compared with isoparse, it is presumably less strict, but both of them are quite forgiving and will attempt to interpret the string that you pass in. If you want to eliminate the possibility of any misreads, you need to use something stricter than either of these functions.

Comparison with Python 3.7+’s built-in datetime.datetime.fromisoformat

datutil.parser.isoparse is a full ISO-8601 format parser, but fromisoformat is deliberately not. Please see the latter function's docs for this cautionary caveat. (See this answer).


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 a date_string in one of the formats emitted by date.isoformat() and datetime.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 8601 strings - 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!


Note in Python 2.6+ and Py3K, the %f character catches microseconds.

>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

See issue here


matomo