python datetul 时区导致错误的小时

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

我使用 datetul 来处理夏令时,但是当我计算 datediff 时,它会导致计算错误。 在下面的代码中,我使用了“America/New_York”,但 dt_159_dateutil 和 dt_300_dateutil 之间的差异应该是 1 秒,但实际上是 3601 秒。 我手动设置时移,结果是1秒。

from datetime import date,timedelta,datetime,timezone
from dateutil import tz


# using dateutl pacage
eastern=tz.gettz("America/New_York")

dt_159_dateutil=datetime(2023,3,12,1,59,59,tzinfo=eastern)
dt_300_dateutil=datetime(2023,3,12,3,0,0,tzinfo=eastern)

# set houst shift manually
est=timezone(timedelta(hours=-5))
edt=timezone(timedelta(hours=-4))
dt_159=datetime(2023,3,12,1,59,59,tzinfo=est)
dt_300=datetime(2023,3,12,3,0,0,tzinfo=edt)



display((dt_300-dt_159).seconds)
# output 1

display((dt_300_dateutil-dt_159_dateutil).seconds)
python-dateutil
1个回答
0
投票

计算差异时,将时间转换为恒定时间,如 UTC。请注意,我已使用 pytz 模块获取下面的 UTC 等效值,因此您可能需要导入它。

显示((dt_300_dateutil.astimezone(pytz.utc)-dt_159_dateutil.astimezone(pytz.utc).astimezone(pytz.utc)).秒)

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