日期时间夏令时转换问题[Python]



由于上周六/周日转换为夏令时,从UTC转换为CET时,我的时间戳字段出现以下错误:

AmbiguousTimeError: Cannot infer dst time from 2020-07-31 11:17:18+00:00, try using the 'ambiguous' argument

#将时间戳字段转换为CET(欧洲、柏林(

df['timestamp_berlin_time'] = df['timestamp'].dt.tz_localize('Europe/Berlin')

我尝试了以下片段:

df['timestamp_berlin_time'] = df['timestamp'].dt.tz_localize('CET',ambiguous='infer')

但这给了我这个错误:

AmbiguousTimeError: 2020-07-31 11:17:18+00:00

数据样本:

0  2020-07-31 11:17:18+00:00
1  2020-07-31 11:17:18+00:00
2  2020-08-31 16:26:42+00:00
3  2020-10-20 07:28:46+00:00
4  2020-10-01 22:11:33+00:00

名称:时间戳,数据类型:datetime64[ns,UTC]

如果您的输入是UTC,但尚未设置UTC,您可以先本地化为UTC,例如:

df['timestamp'] = df['timestamp'].dt.tz_localize('UTC')

如果您的输入已经转换为UTC,您可以简单地使用tz_convert,例如:

s = pd.Series(pd.to_datetime(['2020-10-25 00:40:03.925000', 
'2020-10-25 01:40:03.925000', 
'2020-10-25 02:40:03.925000'], utc=True))
s.dt.tz_convert('Europe/Berlin')
# 0   2020-10-25 02:40:03.925000+02:00
# 1   2020-10-25 02:40:03.925000+01:00
# 2   2020-10-25 03:40:03.925000+01:00
# dtype: datetime64[ns, Europe/Berlin]

如果您的输入时间戳代表当地时间(此处:欧洲/柏林时区(,您可以尝试根据订单推断夏令时转换:

s = pd.Series(pd.to_datetime(['2020-10-25 02:40:03.925000', 
'2020-10-25 02:40:03.925000', 
'2020-10-25 03:40:03.925000']))
s.dt.tz_localize('Europe/Berlin', ambiguous='infer')
# 0   2020-10-25 02:40:03.925000+02:00
# 1   2020-10-25 02:40:03.925000+01:00
# 2   2020-10-25 03:40:03.925000+01:00
# dtype: datetime64[ns, Europe/Berlin]

注:CET不是地理意义上的时区。由于历史原因,pytz可以处理其中一些,但不要指望它。无论如何,它可能会给你静态的tz偏移-如果你希望它包括DST转换,这不是你想要的。

最新更新