我想使用python将此字符串datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT'
转换为时间戳。
我试过
timestamp = time.mktime(time.strptime(datetimestring, '%a, %d %B %Y %H:%M:%S GMT'))
但报告正则表达式错误。
答案 0 :(得分: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
答案 1 :(得分:4)
导入时间 将dateutil.parser导入为dateparser
datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT'
dt = dateparser.parse(datetimestring)
timestamp = int(time.mktime(dt.timetuple()))
答案 2 :(得分:0)
您可以将dateparser用于此目的。
import dateparser
>>> dateparser.parse('Fri, 08 Jun 2012 22:40:26 GMT')
datetime.datetime(2012, 6, 8, 22, 40, 26)