简体   繁体   中英

How to convert string date to a epoch timestamp in python

I have a string date as 2015-03-25T00:00:00Z . How do I convert it to a unix epoch 1426636800000.0

Are there any libraries in python to do that.

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.

>>> 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:

>>> 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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