为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕少森 2024-01-16 15:36:50
由于上周六/周日转换为夏令时,从 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:001  2020-07-31 11:17:18+00:002  2020-08-31 16:26:42+00:003  2020-10-20 07:28:46+00:004  2020-10-01 22:11:33+00:00名称:时间戳,数据类型:datetime64[ns,UTC]
查看完整描述

1 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

如果您的输入是 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]

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


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 转换,那么这不是您想要的。


查看完整回答
反对 回复 2024-01-16
  • 1 回答
  • 0 关注
  • 33 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信