How do I parse an ISO 8601-formatted date?

后端 未结 27 2295
小鲜肉
小鲜肉 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:28

    This works for stdlib on Python 3.2 onwards (assuming all the timestamps are UTC):

    from datetime import datetime, timezone, timedelta
    datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ").replace(
        tzinfo=timezone(timedelta(0)))
    

    For example,

    >>> datetime.utcnow().replace(tzinfo=timezone(timedelta(0)))
    ... datetime.datetime(2015, 3, 11, 6, 2, 47, 879129, tzinfo=datetime.timezone.utc)
    

提交回复
热议问题