Skip to main content
 首页 » 编程设计

python之Pandas tz_localize : Infer dst when localizing timezone in data with duplicates

2025年04月02日8lovecherry

我想用 pandas tz_localize 本地化一个日期时间系列。该系列跨越 DST 日期(例如,德国 CET 为 25Oct2015)。我通常这样做

import pandas as pd 
T = ['25/10/2015 02:59:00','25/10/2015 02:00:00','25/10/2015 02:01:00'] 
pd.to_datetime(T).tz_localize('CET',ambiguous='infer') 

但是当时间序列有重复时——即使它们以明确的方式排序——我得到一个错误:

T = ['25/10/2015 02:59:00','25/10/2015 02:59:00','25/10/2015 02:00:00','25/10/2015 02:01:00'] 
pd.to_datetime(T).tz_localize('CET',ambiguous='infer') 
 
AmbiguousTimeError: There are 2 dst switches when there should only be 1. 

这似乎是一个不必要的限制,因为推断应该非常简单。是否有解决方法或解决方案,或者我是否需要编写自己的推断方法?

请您参考如下方法:

在最新版本中修复了一些 DST 相关的错误,0.19.0rc1 现已发布

In [1]: pd.__version__ 
Out[1]: u'0.19.0rc1' 
 
In [2]: t = ['25/10/2015 02:59:00', '25/10/2015 02:00:00', '25/10/2015 02:01:00'] 
 
In [3]: pd.to_datetime(t).tz_localize('CET',ambiguous='infer') 
Out[3]: DatetimeIndex(['2015-10-25 02:59:00+02:00', '2015-10-25 02:00:00+01:00', '2015-10-25 02:01:00+01:00'], dtype='datetime64[ns, CET]', freq=None)