[英]How do I parse an HTTP date-string in Python?
有沒有一種簡單的方法可以在 Python 中解析 HTTP 日期字符串? 根據標准,有幾種方法可以格式化 HTTP 日期字符串; 該方法應該能夠處理這個問題。
換句話說,我想將像“Wed, 23 Sep 2009 22:15:29 GMT”這樣的字符串轉換為 python 時間結構。
>>> import email.utils as eut
>>> eut.parsedate('Wed, 23 Sep 2009 22:15:29 GMT')
(2009, 9, 23, 22, 15, 29, 0, 1, -1)
如果你想要一個datetime.datetime
對象,你可以這樣做:
def my_parsedate(text):
return datetime.datetime(*eut.parsedate(text)[:6])
從 Python 3.3 開始,有email.utils.parsedate_to_datetime
可以解析RFC 5322時間戳(又名IMF-fixdate
,Internet Message Format 固定長度格式, RFC 7231的HTTP-date
的子集)。
>>> 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)
還有未記錄的http.cookiejar.http2time
可以實現如下相同:
>>> 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)
它在 Python 2.4 中作為cookielib.http2time
引入,用於處理以相同格式表示的 Cookie Expires
指令。
>>> import datetime
>>> datetime.datetime.strptime('Wed, 23 Sep 2009 22:15:29 GMT', '%a, %d %b %Y %H:%M:%S GMT')
datetime.datetime(2009, 9, 23, 22, 15, 29)
httplib.HTTPMessage(filehandle).getdate(headername)
httplib.HTTPMessage(filehandle).getdate_tz(headername)
mimetools.Message(filehandle).getdate()
rfc822.parsedate(datestr)
rfc822.parsedate_tz(datestr)
筆記:
你可以這樣做,如果你只有那一段字符串並且你想解析它:
>>> from rfc822 import parsedate, parsedate_tz
>>> parsedate('Wed, 23 Sep 2009 22:15:29 GMT')
(2009, 9, 23, 22, 15, 29, 0, 1, 0)
>>>
但讓我通過 mime 消息來舉例說明:
import mimetools
import StringIO
message = mimetools.Message(
StringIO.StringIO('Date:Wed, 23 Sep 2009 22:15:29 GMT\r\n\r\n'))
>>> m
<mimetools.Message instance at 0x7fc259146710>
>>> m.getdate('Date')
(2009, 9, 23, 22, 15, 29, 0, 1, 0)
或通過 http 消息(響應)
>>> from httplib import HTTPMessage
>>> from StringIO import StringIO
>>> http_response = HTTPMessage(StringIO('Date:Wed, 23 Sep 2009 22:15:29 GMT\r\n\r\n'))
>>> #http_response can be grabbed via urllib2.urlopen(url).info(), right?
>>> http_response.getdate('Date')
(2009, 9, 23, 22, 15, 29, 0, 1, 0)
對?
>>> import urllib2
>>> urllib2.urlopen('https://fw.io/').info().getdate('Date')
(2014, 2, 19, 18, 53, 26, 0, 1, 0)
在那里,現在我們更多地了解日期格式、mime 消息、mime 工具及其 Python 實現;-)
無論如何,看起來比使用 email.utils 解析 http 標頭更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.