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

编程入门 行业动态 更新时间:2024-10-23 19:20:14
本文介绍了如何在Python中将String Datetime转换为时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I want to convert this string datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT' to timestamp using python.

我尝试了

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

但报告正则表达式错误。

but reports regex error.

推荐答案

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

You're using %B, which corresponds to the full month name, but you only have the abbreviated name. You should use %b instead:

>>> 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中将String Datetime转换为时间戳?

本文发布于:2023-10-27 23:28:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534848.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   时间   如何在   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!