如何在Python中将String Datetime转换为时间戳?

3 python datetime timestamp

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

我试过了

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

但报告正则表达式错误.

DSM*_*DSM 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
Run Code Online (Sandbox Code Playgroud)