如何将 US/Eastern 时区转换为 Python 中的 US/Central

How do I convert US/Eastern timezone to US/Central in Python

我正在尝试将 'US/Eastern' 日期时间转换为另一个时区的等效日期时间,例如 'US/Central'。似乎使用 pytz 和 astimezone 是从以下位置执行此操作的好方法: Converting timezone-aware datetime to local time in Python

import pytz
import datetime as DT
est = pytz.timezone('US/Eastern')
cst = pytz.timezone('US/Central')

我为 est 创建了一个日期时间对象:

ny_dt = DT.datetime(2021, 3, 1, 9, 30, 0, 0, est)

这是 ny_dt 的输出:

Out[6]: datetime.datetime(2021, 3, 1, 9, 30, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)

然后我尝试将此日期时间转换为使用定义的 cst 时区:

chicago_dt = ny_dt.astimezone(cst)

这是 chicago_dt 的输出:

Out[8]: datetime.datetime(2021, 3, 1, 8, 26, tzinfo=<DstTzInfo 'US/Central' CST-1 day, 18:00:00 STD>)

所以这将 930am EST 转换为 826am CST,这是不正确的。应该是中部标准时间上午 830 点,或者恰好早一个小时。做这个的最好方式是什么?谢谢!

import pytz
import datetime as DT
est = pytz.timezone('US/Eastern')
cst = pytz.timezone('US/Central')
ny_dt = DT.datetime(2021, 3, 1, 9, 30, 0, 0)
ny_dt1 = est.localize(ny_dt)
chicago_dt = ny_dt1.astimezone(cst)

输出:

ny_dt1
datetime.datetime(2021, 3, 1, 9, 30, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>)
chicago_dt
datetime.datetime(2021, 3, 1, 8, 30, tzinfo=<DstTzInfo 'US/Central' CST-1 day, 18:00:00 STD>)

来自documentation

This library differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document.