我有以下字符串:
mytime = "2009-03-08T00:27:31.807Z"
如何在 python 中将其转换为纪元?
我试过:
import time
p = '%Y-%m-%dT%H:%M:%S'
int(time.mktime(time.strptime(s, p)))
但它不适用于 31.807Z
。
最佳答案
分为两部分:
- 将时间字符串转换为分割时间。参见 How to parse ISO formatted date in python?
- 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
如果您确定要忽略几分之一秒并获得整数结果:
#!/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
要支持与闰秒相对应的时间戳,例如 Wed July 1 2:59:60 MSK 2015
,您可以 use a combination of time.strptime()
and datetime
(if you care about leap seconds you should take into account the microseconds too) .
关于python - 如何将 python 时间戳字符串转换为纪元?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30468371/