How do I parse an ISO 8601-formatted date?

后端 未结 27 2429
小鲜肉
小鲜肉 2020-11-21 06:08

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

27条回答
  •  Happy的楠姐
    2020-11-21 06:16

    The python-dateutil package can 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 format
    datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
    >>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
    datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
    >>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format
    datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
    >>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only
    datetime.datetime(2008, 9, 3, 0, 0)
    

    Note that dateutil.parser.isoparse is presumably stricter than the more hacky dateutil.parser.parse, 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.

    The Pypi name is python-dateutil, not dateutil (thanks code3monk3y):

    pip install python-dateutil
    

    If you're using Python 3.7, have a look at this answer about datetime.datetime.fromisoformat.

提交回复
热议问题