Convert an RFC 3339 time to a standard Python timestamp

后端 未结 14 1639
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:20

    http://bugs.python.org/issue15873 (duplicate of http://bugs.python.org/issue5207 )

    Looks like there isn't a built-in as of yet.

    0 讨论(0)
  • 2020-12-03 05:23

    rfc3339 library: http://henry.precheur.org/python/rfc3339

    0 讨论(0)
  • 2020-12-03 05:28

    http://pypi.python.org/pypi/iso8601/ seems to be able to parse iso 8601, which RFC 3339 is a subset of, maybe this could be useful, but again, not built-in.

    0 讨论(0)
  • 2020-12-03 05:31

    You don't include an example, but if you don't have a Z-offset or timezone, and assuming you don't want durations but just the basic time, then maybe this will suit you:

    import datetime as dt
    >>> dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')
    datetime.datetime(1985, 4, 12, 23, 20, 50, 520000)
    

    The strptime() function was added to the datetime module in Python 2.5 so some people don't yet know it's there.

    Edit: The time.strptime() function has existed for a while though, and works about the same to give you a struct_time value:

    >>> ts = time.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')
    >>> ts
    time.struct_time(tm_year=1985, tm_mon=4, tm_mday=12, tm_hour=23, tm_min=20, tm_sec=50, tm_wday=4, tm_yday=102, tm_isdst=-1)
    >>> time.mktime(ts)
    482210450.0
    
    0 讨论(0)
  • 2020-12-03 05:32

    feedparser.py provides robust/extensible way to parse various date formats that may be encountered in real-world atom/rss feeds:

    >>> from feedparser import _parse_date as parse_date
    >>> parse_date('1985-04-12T23:20:50.52Z')
    time.struct_time(tm_year=1985, tm_mon=4, tm_mday=12, tm_hour=23, tm_min=20,
                     tm_sec=50, tm_wday=4, tm_yday=102, tm_isdst=1)
    
    0 讨论(0)
  • 2020-12-03 05:33

    I have been doing a deep dive in dateimes and RFC3339 and recently come across the arrow library and have just used and solved my problem:

    import arrow
    
    date_string = "2015-11-24 00:00:00+00:00"
    my_datetime = arrow.get(date_string).datetime
    
    0 讨论(0)
提交回复
热议问题