You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中America/New_York时区偏移显示-04:56而非-04:00的问题求助

问题原因及解决方法

为什么会出现-04:56的偏移?

你直接将pytz.timezone('America/New_York')作为datetime.datetime的tzinfo参数传入,这会导致Python使用纽约时区的本地平均时间(LMT)偏移,而非当前夏令时的-04:00偏移。

pytz的时区对象包含该时区所有历史时区变更记录(比如夏令时切换、时区偏移调整),但直接赋值给tzinfo时,datetime无法自动匹配对应日期的正确偏移,只会取该时区最早期的LMT偏移(纽约的LMT偏移恰好是-04:56)。

正确的实现方式

方式1:使用pytz的localize()方法(兼容旧版本)

先创建不带时区的naive datetime,再用pytz时区对象的localize()方法绑定对应日期的正确时区偏移:

import datetime
import pytz

est = pytz.timezone('America/New_York')
# 创建无时区的datetime,通过localize绑定正确时区
myDateTime = est.localize(datetime.datetime(year=2024, month=8, day=15, hour=17, minute=00))
print("America/New_York: ", myDateTime.isoformat())
print("UTC:              ", myDateTime.astimezone(pytz.utc).isoformat())

运行后会输出正确结果:

America/New_York:  2024-08-15T17:00:00-04:00
UTC:               2024-08-15T21:00:00+00:00

方式2:使用Python 3.9+标准库zoneinfo(推荐)

Python 3.9及以上自带zoneinfo模块,无需额外安装pytz,且支持直接将时区对象传给tzinfo参数:

import datetime
from zoneinfo import ZoneInfo

est = ZoneInfo('America/New_York')
myDateTime = datetime.datetime(year=2024, month=8, day=15, hour=17, minute=00, tzinfo=est)
print("America/New_York: ", myDateTime.isoformat())
print("UTC:              ", myDateTime.astimezone(ZoneInfo('UTC')).isoformat())

此方式同样会输出正确的时区偏移结果。

内容的提问来源于stack exchange,提问作者Steven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 00:42:43