最近我的Python Pandas代码坏了。问题是从过去使用过的时间戳列表创建DateTimeIndex。我最初的想法是,时间戳以某种方式具有无效的格式,但是经过一些调试后,我注意到直到列表中的条目号102为止,转换为DateTimeIndex都有效
>>> pd.to_datetime(df.created.head(n=102))
datetime
...
2019-10-28 15:16:24+01:00 2019-10-28 15:16:24+01:00
2019-10-28 14:50:54+01:00 2019-10-28 14:50:54+01:00
Name: created,Length: 102,dtype: datetime64[ns,pytz.FixedOffset(60)]
但是列表中的下一个条目默默地中断了DateTimeIndex的创建。熊猫只返回dtype: object instead
的列表:
>>> pd.to_datetime(df.created.head(n=103))
datetime
...
2019-10-28 15:16:24+01:00 2019-10-28 15:16:24+01:00
2019-10-28 14:50:54+01:00 2019-10-28 14:50:54+01:00
2019-10-25 15:06:57+02:00 2019-10-25 15:06:57+02:00
Name: created,Length: 103,dtype: object
盯着时间戳记后,我终于指出,问题必须是由于夏令时的结束而造成的时区偏移。重现此问题的一个最小示例是:
# works
>>> import pandas as pd
>>> pd.to_datetime(["2019-11-20 11:46:32+01:00"])
DatetimeIndex(['2019-11-20 11:46:32+01:00'],dtype='datetime64[ns,pytz.FixedOffset(60)]',freq=None)
# works
>>> pd.to_datetime(["2019-10-25T15:06:57.000+0200"])
DatetimeIndex(['2019-10-25 15:06:57+02:00'],pytz.FixedOffset(120)]',freq=None)
# doesn't work
>>> pd.to_datetime(["2019-11-20 11:46:32+01:00","2019-10-25T15:06:57.000+0200"])
Index([2019-11-20 11:46:32+01:00,2019-10-25 15:06:57+02:00],dtype='object')
这是Bug还是Pandas的功能?为什么熊猫不给出警告或错误,因为它不能将时间戳转换为DateTimeIndex。以及如何解决我的代码,以便将具有可变时区偏移量的时间戳成功转换为DateTimeIndex?