Convert an RFC 3339 time to a standard Python timestamp

后端 未结 14 1911
Happy的楠姐
Happy的楠姐 2020-12-03 04:40

Is there an easy way to convert an RFC 3339 time into a regular Python timestamp?

I\'ve got a script which is reading an ATOM feed and I\'d like to be able to compar

14条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 05:17

    The new datetime.fromisoformat(date_string) method which was added in Python 3.7 will parse most RFC 3339 timestamps, including those with time zone offsets. It's not a full implementation, so be sure to test your use case.

    >>> from datetime import datetime
    >>> datetime.fromisoformat('2011-11-04')
    datetime.datetime(2011, 11, 4, 0, 0)
    >>> datetime.fromisoformat('2011-11-04T00:05:23')
    datetime.datetime(2011, 11, 4, 0, 5, 23)
    >>> datetime.fromisoformat('2011-11-04 00:05:23.283')
    datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
    >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
    datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
    >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00')   
    datetime.datetime(2011, 11, 4, 0, 5, 23,
        tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
    

提交回复
热议问题