使用pytz和datetime获取27/02/2019 00:00 US / Eastern在python中的时间戳

问题描述 投票:0回答:1

我有以下字符串:

27/02/2019

由于在程序中已知这些日期对应于NY时区,我想获得对应于以下内容的时间戳:

27/02/2019 00:00 US/Eastern

我试过了:

import datetime
import pytz

exchange_tz = pytz.timezone('US/Eastern')
_period1 = datetime.datetime(2019,2,27)
_period1_localized = exchange_tz.localize(_period1)
_period1_ts = int((_period1_localized - datetime.datetime(1970, 1, 1, tzinfo=exchange_tz)).total_seconds()) 

>>> _period1_ts
1551225600

但是这给出了对应的时间戳:

27/02/2019 00:00 UTC

我已经检查过1551225600时间戳对应27/02/2019 00:00 UTC而不是27/02/2019 00:00 US/Eastern使用此服务:

https://www.epochconverter.com/

我究竟做错了什么?

python python-2.7 datetime timestamp pytz
1个回答
1
投票

为了防止其他人,我发现错误位于此处:

_period1_ts = int((_period1_localized - datetime.datetime(1970, 1, 1, tzinfo=exchange_tz)).total_seconds())

它应使用UTC时区作为EPOCH时间:

_period1_ts = int((_period1_localized - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())

通过这样做你得到1551243600作为时间戳,这对应于Wednesday, 27 February 2019 05:00:00 UTC,这是有效的27/02/2019 00:00 US/Eastern time

具有此更正的上述代码可用于从本地化日期时间获取时间戳。

© www.soinside.com 2019 - 2024. All rights reserved.