简体   繁体   中英

How to convert time to timestamp?

A time string like this: 'Thu Nov 26 17:49:28 +0000 2015' .

Need to convert it to UTC timestamp, tried several methods found from online, but not work.

What's the correct way to convert it? Thx.

Use datetime.datetime.strptime() with the proper format specifier, and then use the timestamp() method:

>>> import datetime
>>> d = 'Thu Nov 26 17:49:28 +0000 2015'
>>> datetime.datetime.strptime(d, '%a %b %d %H:%M:%S %z %Y').timestamp()
1448560168.0

To get "seconds since epoch" from an rfc 5322 date-time string (like in email Date header):

>>> from email.utils import parsedate_tz, mktime_tz
>>> mktime_tz(parsedate_tz('Thu Nov 26 17:49:28 +0000 2015'))
1448560168

If you like Pandas, this is very simple

In [32]: import pandas as pd
# Construct date time index
In [33]: dt_index = pd.DatetimeIndex(['Thu Nov 26 17:49:28 +0000 2015'])
# Get the epoch timestamp in seconds
In [35]: dt_index.astype('int64')/1e9
Out[35]: array([  1.44856017e+09])

In [36]: dt_index.astype('int64')[0]/1e9
Out[36]: 1448560168.0

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