pandas.Timestamp与Python datetime时区偏移差异:是否需提交Bug?
pandas.Timestamp与Python datetime时区偏移不一致问题
问题现象
将naive日期转换为Europe/Paris时区的aware类型时,pandas.Timestamp与Python原生datetime的时区偏移结果不一致:前者显示+02:00,后者显示+01:00。该差异仅出现在特定日期。
触发差异的特定日期
d=2010-10-31 02:00:00 d=2011-10-30 02:00:00 d=2012-10-28 02:00:00 d=2013-10-27 02:00:00 d=2014-10-26 02:00:00 d=2015-10-25 02:00:00 d=2016-10-30 02:00:00 d=2017-10-29 02:00:00 d=2018-10-28 02:00:00 d=2019-10-27 02:00:00 d=2020-10-25 02:00:00 d=2021-10-31 02:00:00 d=2022-10-30 02:00:00
复现代码与环境
复现代码
from dateutil import parser import pytz import pandas as pd d = '2022-10-30 02:00:00' ts = pytz.timezone('Europe/Paris').localize(pd.Timestamp(d)) dt = pytz.timezone('Europe/Paris').localize(parser.parse(d)) print(ts) # 输出:2022-10-30 02:00:00+02:00 print(dt) # 输出:2022-10-30 02:00:00+01:00
环境信息
/Users/puiseux/opt/miniconda3/envs/python311/lib/python3.11/site-packages/_distutils_hack/__init__.py:33: UserWarning: Setuptools is replacing distutils. warnings.warn("Setuptools is replacing distutils.") INSTALLED VERSIONS ------------------ commit : 2e218d10984e9919f0296931d92ea851c6a6faf5 python : 3.11.0.final.0 python-bits : 64 OS : Darwin OS-release : 21.6.0 Version : Darwin Kernel Version 21.6.0: Thu Sep 29 20:12:57 PDT 2022; root:xnu-8020.240.7~1/RELEASE_X86_64 machine : x86_64 processor : i386 byteorder : little LC_ALL : None LANG : None LOCALE : fr_FR.UTF-8 pandas : 1.5.3 numpy : 1.24.2 pytz : 2022.7.1 dateutil : 2.8.2 setuptools : 65.5.0 pip : 22.2.2 Cython : None pytest : None hypothesis : None sphinx : None blosc : None feather : None xlsxwriter : None lxml.etree : None html5lib : None pymysql : None psycopg2 : None jinja2 : 3.1.2 IPython : None pandas_datareader: None bs4 : None bottleneck : None brotli : None fastparquet : None fsspec : None gcsfs : None matplotlib : 3.7.0 numba : None numexpr : None odfpy : None openpyxl : None pandas_gbq : None pyarrow : 11.0.0 pyreadstat : None pyxlsb : None s3fs : None scipy : 1.10.0 snappy : None sqlalchemy : 2.0.4 tables : None tabulate : 0.9.0 xarray : None xlrd : None xlwt : None zstandard : None tzdata : 2022.7
问题分析
上述日期均为欧洲夏令时切换至冬令时的时间点:巴黎时区在每年10月最后一个周日的02:00会将时钟回拨至01:00,因此02:00:00这个时间会重复出现两次——一次属于夏令时(偏移+02:00),一次属于冬令时(偏移+01:00),属于歧义时间。
pytz的localize方法处理歧义时间时,若未指定is_dst参数,理论上会抛出AmbiguousTimeError,但实际测试中,pandas.Timestamp与原生datetime的处理逻辑出现分歧:
- 原生
datetime被localize时默认选择了冬令时对应的偏移(+01:00) pandas.Timestamp被localize时默认选择了夏令时对应的偏移(+02:00)
这种行为差异源于pandas对pytz时区处理的内部实现与原生datetime的兼容问题,属于pandas与第三方时区库交互时的一致性Bug。
结论
该差异属于pandas的Bug,建议向pandas官方团队提交Bug报告,提交时需包含完整的复现代码、环境信息及触发差异的日期列表,以帮助开发团队定位问题。
内容的提问来源于stack exchange,提问作者Pierre Puiseux
相关产品推荐
相关产品推荐

