如何将字符串日期转换为python中的纪元时间戳

问题描述:

我有一个字符串日期为2015-03-25T00:00:00Z。我如何将它转换为unix时代1426636800000.0如何将字符串日期转换为python中的纪元时间戳

Python中是否有任何库可以这样做。

+0

这看起来像一个ISO日期已经回答[这里](http://*.com/questions/127803/how-to-parse-iso-formatted-date-in-python) – 2015-03-25 11:01:21

+0

另外,你可以看到一些在http://*.com /问题/ 11743 019 /转换的Python-日期时间到划时代与-的strftime。 – user1929959 2015-03-25 11:02:13

使用时间,例如。

所以首先你需要将字符串转换为时间对象(或者你可以使用datetime或halex提到的方式),然后获得自epoch以来的秒数。

>>> import time 
>>> time.mktime(time.strptime('2015-03-25T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ')) 
1427241600.0 

time.strptime(string[, format])

import time 

print time.strptime("2015-03-25T00:00:00Z","%Y-%m-%dT%H:%M:%SZ") 

如果你有Python的3.3或更新版本,你可以使用datetime模块:

>>> import datetime 
>>> datetime.datetime.strptime("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ").timestamp() 
1427238000.0 
+0

AttributeError:'datetime.datetime'对象没有属性'timestamp'是抛出的错误 – user2890683 2015-03-25 11:14:17

+0

@ user2890683哦。我忘了提及['timestamp'](https://docs.python.org/3.4/library/datetime.html#datetime.datetime.timestamp)是在Python 3.3中引入的。好像你正在使用Python2。抱歉给你带来不便。 – halex 2015-03-25 11:15:53

您可以使用easy_date以方便:

import date_converter 
timestamp = date_converter.string_to_timestamp("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ")