[英]How to convert python timestamp string to epoch?
I have the following string:我有以下字符串:
mytime = "2009-03-08T00:27:31.807Z"
How do I convert it to epoch in python?如何在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
.但它不适用于
31.807Z
。
There are two parts:有两个部分:
#!/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) .要支持对应于闰秒的时间戳,例如
Wed July 1 2:59:60 MSK 2015
,您可以使用time.strptime()
和datetime
的组合(如果您关心闰秒,您也应该考虑微秒) 。
You are missing .%fZ
from your format string.您的格式字符串中缺少
.%fZ
。
p = '%Y-%m-%dT%H:%M:%S.%fZ'
The correct way to convert to epoch is to use datetime
:转换为纪元的正确方法是使用
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.或者,如果您想忽略分数,请调用 int。
dateutil is the only library i have found that correctly deals with the timezone offset identitifier ( Z
) dateutil 是我发现的唯一一个正确处理时区偏移标识符(
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())
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:笔记:
time.strptime()
, the returned time.struct_time
does not support sub-second precision.time.strptime()
,返回的time.struct_time
不支持亚秒级精度。%f
format is for microseconds. %f
格式用于微秒。 When parsing it need not be the full 6 digits.dateutil
has recently been added back to python packages, it's an easy one liner that handles formatting on its own. dateutil
最近已重新添加到 python 包中,它是一个简单的单行程序,可以自行处理格式。
from dateutil import parser
strtime = '2009-03-08T00:27:31.807Z'
epoch = parser.parse(strtime).timestamp()
Python 3.7+ The string format in question can be parsed by strptime
: Python 3.7+ 有问题的字符串格式可以通过
strptime
解析:
from datetime import datetime
datetime.strptime("2009-03-08T00:27:31.807Z", '%Y-%m-%dT%H:%M:%S.%f%z')
>>> datetime.datetime(2009, 3, 8, 0, 27, 31, 807000, tzinfo=datetime.timezone.utc)
Another option using the built-in datetime.fromisoformat()
: As mentioned in this thread linked by @jfs, fromisoformat()
doesn't parse the 'Z' character to UTC although this is part of the RFC3339 definitions.使用内置
datetime.fromisoformat()
另一个选项:如@jfs 链接的此线程中所述, fromisoformat()
不会将“Z”字符解析为 UTC,尽管这是RFC3339定义的一部分。 A little work-around can make it work - some will consider this nasty but it's efficient after all.一些变通办法可以使它工作 - 有些人会认为这很讨厌,但毕竟它是有效的。
from datetime import datetime
mytime = "2009-03-08T00:27:31.807Z"
datetime.fromisoformat(mytime.replace("Z", "+00:00")).timestamp()
>>> 1236472051.807
This code works in Python 3.6 to convert a datetime string to epoch in UTC or local timezone.此代码适用于 Python 3.6,可将日期时间字符串转换为 UTC 或本地时区中的纪元。
from datetime import datetime, timedelta
from dateutil.tz import tzutc, tzlocal
mydate = '2020-09-25'
mytime = '06:00:00'
epoch1970 = datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
myepochutc = int((datetime.strptime(mydate + ' ' + mytime, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tzutc()) - epoch1970).total_seconds()*1000)
myepochlocal = int((datetime.strptime(mydate + ' ' + mytime, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tzlocal()) - epoch1970).total_seconds()*1000)
#epoch will be in milliseconds
print(myepochutc) #if mydate/mytime was in utc
print(myepochlocal) #if mydate/mytime was in local timezone
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.