首页 > 解决方案 > 将时间转换为 EpochSecond

问题描述

我是 python 新手。目前,我有一个像“2018-11-15 13:34:40.000 EST”这样的时间数据。我想把它转换成EpochSecond。

我知道如何使用 dateparser 来获得这个,但是,我想知道有没有一种简单的方法可以在没有 dateparser 的情况下做到这一点?

import dateparser
from datetime import datetime, timezone

mytime = "2018-11-15 13:34:40.000 EST"

dateVar = dateparser.parse(mytime)

print(dateVar)

epoch = datetime(1970, 1, 1,  tzinfo=timezone.utc)

print((dateVar - epoch).total_seconds()) 

标签: pythonpython-3.xepoch

解决方案


datetime.datetime.timestamp()是您正在寻找的(相关部分):

对于感知日期时间实例,返回值计算为:

(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

例子:

import datetime

now = datetime.datetime.now()
epoch = now.timestamp()

# 1542394106.155199

实施到您的示例中,我们将不得不使用另一种方法,因为由于错误(我在哪里找到信息的相关问题datetime.datetime.strptime())而不太友好地采用时区。所以我们必须使用另一个内置函数来解析它(这里的例子):

from dateutil.parser import parse

mytime = "2018-11-12 00:30:20.000 EST"
dt = parse(mytime)
epoch = dt.timestamp()

解析后的字符串仍然是一个datetime.datetime对象,因此您可以在解析后对其进行相同的处理。

注意:但是parse可能会抱怨它读取了时区但不理解它:

 UnknownTimezoneWarning: tzname EDT identified but not understood.  Pass `tzinfos` argument in order to correctly return a timezone-aware datetime.  In a future version, this will raise an exception.

无论如何,您最终可能需要将传递给tzinfosparse()方法:

from dateutil.parser import parse
# from dateutil.tz import gettz # <-- can use if you know the tz to retrieve

tzinfos = {'EST': -18000, 'CET': +3600}
# another example: {"CST": gettz("America/Chicago")}
mytime = "2018-11-12 00:30:20.000 EST"
dt = parse(mytime, tzinfos=tzinfos)
epoch = dt.timestamp()
print(epoch)

所以我想最终它并不像你想要的那么简单。


推荐阅读