How do I parse an HTTP date-string in Python?

前端 未结 4 1167
眼角桃花
眼角桃花 2020-12-08 02:34

Is there an easy way to parse HTTP date-strings in Python? According to the standard, there are several ways to format HTTP date strings; the method should be able to handle

4条回答
  •  醉酒成梦
    2020-12-08 02:48

    Since Python 3.3 there's email.utils.parsedate_to_datetime which can parse RFC 5322 timestamps (aka IMF-fixdate, Internet Message Format fixed length format, a subset of HTTP-date of RFC 7231).

    >>> from email.utils import parsedate_to_datetime
    ... 
    ... s = 'Sun, 06 Nov 1994 08:49:37 GMT'
    ... parsedate_to_datetime(s)
    0: datetime.datetime(1994, 11, 6, 8, 49, 37, tzinfo=datetime.timezone.utc)
    

    There's also undocumented http.cookiejar.http2time which can achieve the same as follows:

    >>> from datetime import datetime, timezone
    ... from http.cookiejar import http2time
    ... 
    ... s = 'Sun, 06 Nov 1994 08:49:37 GMT'
    ... datetime.utcfromtimestamp(http2time(s)).replace(tzinfo=timezone.utc)
    1: datetime.datetime(1994, 11, 6, 8, 49, 37, tzinfo=datetime.timezone.utc)
    

    It was introduced in Python 2.4 as cookielib.http2time for dealing with Cookie Expires directive which is expressed in the same format.

提交回复
热议问题