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

Python中tz_localize引发NonExistentTimeError在不同设备上表现差异的技术求助

datetime.tz_localize抛出NonExistentTimeError:Windows Server与本地环境的差异问题

问题背景与现象

最近我在处理PIMS系统的历史数据时,碰到了一个关于datetime模块tz_localize函数的奇怪跨环境问题:

  • 运行代码时,Windows Server 2016服务器上会触发大量pytz.NonExistentTimeError报错
  • 但在我的笔记本电脑上,执行完全相同的代码、处理同一时间段的数据时,却没有任何异常

更让人困惑的是,服务器和笔记本的自动夏令时设置都是IT部门统一配置开启的,我没有权限关闭该设置。而我所在地区原本计划启用夏令时,但今年临时取消了这个安排。

初始代码如下:

infer_dst = np.array([False]*df.shape[0])
try:
    df.index=df.index.tz_localize(self.tzs,ambiguous=infer_dst)
except pytz.NonExistentTimeError as e:
    self.logger.warning(f"DST between {t_ini} and {t_end} in host {ctrl_inf['host']}")
    self.logger.warning(str(e))

问题定位与临时解决方案

经过排查,确认异常仅出现在Windows Server环境中,且集中在**2021年11月7日0点到1点(24小时制)**的时间段。由于无法修改服务器的时区设置,我临时采用了一个不算优雅但有效的解决办法:逐个检查索引并移除存在问题的时间点,再重新执行时区本地化操作。

修改后的代码:

infer_dst = np.array([False]*df1.shape[0])
try:
    df1.index=df1.index.tz_localize(self.tzs,ambiguous=infer_dst)
except pytz.NonExistentTimeError as e:
    self.logger.warning(f'DST between {t_ini} and {t_end} in host {host}')
    self.logger.warning(str(e))
    # 尝试移除存在问题的时间段
    remove_index=[]
    for k in range(len(df1)-1):
        try:
            df1.index[k].tz_localize(self.tzs)
        except:
            remove_index.append(k)
    df1.drop(df1.index[remove_index],inplace=True)
    infer_dst = np.array([False]*df1.shape[0])
    df1.index=df1.index.tz_localize(self.tzs,ambiguous=infer_dst)

我推测问题根源可能是Windows Server的时区数据库未更新到“取消夏令时”的最新配置,导致系统认为该时间段是夏令时切换的不存在时间,而本地笔记本的时区数据已同步更新,因此没有触发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 00:57:46