将时间转换为 EpochSecond

Convert Time to 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()) 

尝试:

from datetime import datetime

epoch = datetime.datetime(1970,1,1)
i = datetime.now()

delta_time = (i - epoch).total_seconds()

datetime.datetime.timestamp() 就是你要找的(相关部分):

For aware datetime instances, the return value is computed as:

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

示例:

import datetime

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

# 1542394106.155199

实施到您的示例中,我们将不得不使用另一种方法 datetime.datetime.strptime() doesn't quite take timezone kindly due to a bug (relevant question where I found the info). So we'll have to use another builtin to parse it (example here):

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.

你可能最终需要 pass the tzinfos into the parse() method 无论如何:

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)

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