How to convert python timestamp string to epoch?

大憨熊 提交于 2019-11-30 03:52:06

问题


I have the following string:

mytime = "2009-03-08T00:27:31.807Z"

How do I convert it to epoch in python?

I tried:

import time
p = '%Y-%m-%dT%H:%M:%S'
int(time.mktime(time.strptime(s, p)))

But it does not work with the 31.807Z.


回答1:


There are two parts:

  1. Convert the time string into a broken-down time. See How to parse ISO formatted date in python?
  2. Convert the UTC time to "seconds since the Epoch" (POSIX timestamp).
#!/usr/bin/env python
from datetime import datetime

utc_time = datetime.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = (utc_time - datetime(1970, 1, 1)).total_seconds()
# -> 1236472051.807

If you are sure that you want to ignore fractions of a second and to get an integer result:

#!/usr/bin/env python
import time
from calendar import timegm

utc_time = time.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = timegm(utc_time)
# -> 1236472051

To support timestamps that correspond to a leap second such as Wed July 1 2:59:60 MSK 2015, you could use a combination of time.strptime() and datetime (if you care about leap seconds you should take into account the microseconds too).




回答2:


You are missing .%fZ from your format string.

p = '%Y-%m-%dT%H:%M:%S.%fZ'

The correct way to convert to epoch is to use datetime:

from datetime import datetime

p = '%Y-%m-%dT%H:%M:%S.%fZ'
mytime = "2009-03-08T00:27:31.807Z"
epoch = datetime(1970, 1, 1)
print((datetime.strptime(mytime, p) - epoch).total_seconds())

Or call int if you want to ignore fractions.




回答3:


dateutil is the only library i have found that correctly deals with the timezone offset identitifier (Z)

pip install python-dateutil

then

from dateutil.parser import parse as date_parse
print date_parse("2009-03-08T00:27:31.807Z")
#get timestamp

import calendar
dt =  date_parse("2009-03-08T00:27:31.807Z")
timestamp1 = calendar.timegm(dt.timetuple())



回答4:


Code:

import datetime
epoch = datetime.datetime(1970, 1, 1)

mytime = "2009-03-08T00:27:31.807Z"
myformat = "%Y-%m-%dT%H:%M:%S.%fZ"
mydt = datetime.datetime.strptime(mytime, myformat)
val = (mydt - epoch).total_seconds()

print(val)
> 1236472051.81
repr(val)
> '1236472051.807'

Notes:

  • When using time.strptime(), the returned time.struct_time does not support sub-second precision.
  • The %f format is for microseconds. When parsing it need not be the full 6 digits.


来源:https://stackoverflow.com/questions/30468371/how-to-convert-python-timestamp-string-to-epoch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!