如何将python时间戳字符串转换为纪元? [英] How to convert python timestamp string to epoch?
本文介绍了如何将python时间戳字符串转换为纪元?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串:
mytime = "2009-03-08T00:27:31.807Z"
如何在python中将其转换为纪元?
How do I convert it to epoch in python?
我尝试过:
import time
p = '%Y-%m-%dT%H:%M:%S'
int(time.mktime(time.strptime(s, p)))
但不适用于 31.807Z
。
推荐答案
有两个部分:
- 将时间字符串转换为细分时间。请参阅如何在python中解析ISO格式的日期?
- 将UTC时间转换为自纪元以来的秒数(POSIX时间戳)。
- Convert the time string into a broken-down time. See 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
如果您确定要忽略一小数秒并获得整数结果:
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
支持与a秒相对应的时间戳,例如 7月1日星期三2:59:60 MSK 2015
,则可以结合使用 time.strptime ()
和 datetime
(如果您关心leap秒,也应该考虑微秒)。
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).
这篇关于如何将python时间戳字符串转换为纪元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文