python - 如何在 Python 中将字符串日期时间转换为时间戳?

标签 python datetime timestamp

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

我试过了

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

但报告正则表达式错误。

最佳答案

您正在使用 %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

关于python - 如何在 Python 中将字符串日期时间转换为时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10957522/

相关文章:

python - MAXent分类器NLTK输出理解

c# - 如果结构包含 DateTime 字段,为什么 LayoutKind.Sequential 的工作方式不同?

c# - DateTime 格式注释不适用于 Visual Studio 中的 Vue 应用程序

oracle - 在oracle中查询日期时间

timestamp - unix 时间戳是存储时间戳的最佳方式吗?

ios - 将NSDate格式化为YYYYMMDDHHMMSS.XXX [gmt offset [:tz name]]

python - 为什么 turtle.circle(r,extent=720,steps=5) 在 python 中画了一颗星?

python - 等待值然后停止服务器,在 'werkzeug.server.shutdown' 被弃用并删除之后

python - 让 python 导入 uno/pyuno

scala - 在 Spark Scala 中将时间戳转换为 UTC