How do I parse an ISO 8601-formatted date?

后端 未结 27 2309
小鲜肉
小鲜肉 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条回答
  •  我在风中等你
    2020-11-21 06:20

    New in Python 3.7+


    The datetime standard library introduced 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().

    Example of use:

    from datetime import datetime
    
    date = datetime.fromisoformat('2017-01-01T12:30:59.000000')
    

提交回复
热议问题