3

我想datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT'使用 python 将此字符串转换为时间戳。

我试过了

 timestamp = time.mktime(time.strptime(datetimestring, '%a, %d %B %Y %H:%M:%S GMT'))

但报告正则表达式错误。

4

3 回答 3

6

您正在使用%B,它对应于完整的月份名称,但您只有缩写名称。您应该%b改用:

>>> import time
>>> datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT' 
>>> timestamp = time.mktime(time.strptime(datetimestring, '%a, %d %B %Y %H:%M:%S GMT'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Fri, 08 Jun 2012 22:40:26 GMT' does not match format '%a, %d %B %Y %H:%M:%S GMT'
>>> timestamp = time.mktime(time.strptime(datetimestring, '%a, %d %b %Y %H:%M:%S GMT'))
>>> timestamp
1339209626.0
于 2012-06-09T00:52:45.767 回答
4

导入时间导入 dateutil.parser 作为 dateparser

datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT'
dt = dateparser.parse(datetimestring)
timestamp = int(time.mktime(dt.timetuple()))
于 2014-06-18T08:24:25.243 回答
0

为此,您可以使用dateparser

import dateparser >>> dateparser.parse('Fri, 08 Jun 2012 22:40:26 GMT') datetime.datetime(2012, 6, 8, 22, 40, 26)

于 2016-09-28T18:53:45.820 回答