如何将python timestamp string转换为epoch?

时间:2015-05-26 20:34:00

标签: python timestamp epoch

我有以下字符串:

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

7 个答案:

答案 0 :(得分:15)

分为两部分:

  1. 将时间字符串转换为细分时间。请参阅How to parse ISO formatted date in python?
  2. Convert the UTC time to "seconds since the Epoch" (POSIX timestamp)
  3. #!/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)

答案 1 :(得分:8)

您的格式字符串中缺少.%fZ

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

转换为纪元的正确方法是使用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())

如果你想忽略分数,可以调用int。

答案 2 :(得分:3)

dateutil是我发现的唯一能够正确处理时区偏移识别符(Z)的库

pip install python-dateutil

然后

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())

答案 3 :(得分:1)

代码:

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'

注意:

  • 使用time.strptime()时,返回的time.struct_time不支持亚秒精度。
  • %f format是微秒。解析时不必是完整的6位数。

答案 4 :(得分:0)

Python 3.7 + 可以由echo -n '{"@timestamp":"2020-06-18T11:52:37.391","severity":"INFO", "message":"Processing request started"}' > /dev/udp/HOST/PORT 解析有问题的字符串格式:

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) 的选项:如@jfs链接的this线程中所述,datetime.fromisoformat()不会将'Z'字符解析为UTC,尽管这是一部分RFC3339的定义。采取一些变通办法可以使其正常工作-有些人会认为这很讨厌,但毕竟是efficient

fromisoformat()

答案 5 :(得分:0)

此代码在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

答案 6 :(得分:0)

dateutil 最近被重新添加到 python 包中,它是一个简单的单行代码,可以自行处理格式。

from dateutil import parser
strtime = '2009-03-08T00:27:31.807Z'
epoch = parser.parse(strtime).timestamp()