简体   繁体   English

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

[英]How to convert string date to a epoch timestamp in python

I have a string date as 2015-03-25T00:00:00Z . 我有一个字符串日期为2015-03-25T00:00:00Z How do I convert it to a unix epoch 1426636800000.0 如何将其转换为Unix纪元1426636800000.0

Are there any libraries in python to do that. python中是否有任何库可以做到这一点。

time.strptime(string[, format]) time.strptime(string [,format])

import time

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

Using time, for example. 例如,使用时间。

So first you need to convert the string to time object (or you can use datetime alternatively as halex mentioned) and then get the seconds since epoch. 因此,首先需要将字符串转换为时间对象(或者您可以使用datetime或halex),然后获取自纪元以来的秒数。

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

If you have Python 3.3 or newer you can use the datetime module: 如果您拥有Python 3.3或更高版本,则可以使用datetime模块:

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

You can use easy_date to make it easy: 您可以使用easy_date使其变得容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM