使用pytz和datetim在python中获取2019年2月27日00:00美国/东部的时间戳

2024-10-01 09:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串:

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/

我做错什么了?你知道吗


Tags: 字符串import程序datetimeexchange时间localizedtz
1条回答
网友
1楼 · 发布于 2024-10-01 09:15:59

为了以防万一,我发现错误就在这里:

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

应使用UTC时区作为历元时间:

_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

上面带有此更正的代码可用于从本地化的datetime获取时间戳。你知道吗

相关问题 更多 >