提问人:ivar martens 提问时间:10/6/2023 最后编辑:ivar martens 更新时间:10/9/2023 访问量:51
如何更正具有日期时间列的数据帧,以便正确添加时区,包括 DST 更改?(蟒蛇)
How can I correct a dataframe with a datetime column so that the timezones are correctly added including DST changes? (Python)
问:
我拥有的数据帧有一个没有时区的列。但是由于 DST 更改,我在数据操作方面遇到了一些问题。这些问题是由于当时钟向前改变时“缺失”行和当时钟向后改变时“重复”行造成的。
我编写了一个函数来添加时区,该时区会自动将 DST 计入计数。
def fix_dutch_clock_shift(df):
df_fixed = df.copy()
pd.to_datetime(df_fixed['datetime'])
amsterdam_tz = pytz.timezone('Europe/Amsterdam')
for index, row in df_fixed.iterrows():
dt = row['datetime']
dt = amsterdam_tz.localize(dt)
df_fixed.at[index, 'datetime'] = dt
return df_fixed
这对于在正确的日期时间将时区从 +01:00 更改为 +01:00 更改为 +02:00 的时钟非常有效,但对于倒退的时钟,我仍然有重复项。
Datetime, Long, Short
2022-10-30 02:00:00+02:00,61.58,61.58
2022-10-30 02:15:00+02:00,49.98,49.98
2022-10-30 02:30:00+02:00,26.72,26.72
2022-10-30 02:45:00+02:00,-111.32,-111.32
2022-10-30 02:00:00+02:00,-111.32,-111.32
2022-10-30 02:15:00+02:00,-130.19,-130.19
2022-10-30 02:30:00+02:00,-6.69,-6.69
2022-10-30 02:45:00+02:00,-130.19,-130.19
但我希望时区在第二次到达 2022-10-30 02:00 时从 +02:00 移回 +01:00。
Datetime, Long, Short
2022-10-30 02:00:00+02:00,61.58,61.58
2022-10-30 02:15:00+02:00,49.98,49.98
2022-10-30 02:30:00+02:00,26.72,26.72
2022-10-30 02:45:00+02:00,-111.32,-111.32
2022-10-30 02:00:00+01:00,-111.32,-111.32
2022-10-30 02:15:00+01:00,-130.19,-130.19
2022-10-30 02:30:00+01:00,-6.69,-6.69
2022-10-30 02:45:00+01:00,-130.19,-130.19
答:
0赞
FObersteiner
10/9/2023
#1
IIUC,您的日期时间数据在全年具有 UTC 偏移量 (+02:00),应为 +01:00 或 +02:00,具体取决于 DST 是否处于活动状态。
您可以通过先删除偏移量,然后设置正确的时区来实现此目的:
# to datetime, then remove UTC offset (+02:00)
df["dt"] = pd.to_datetime(df["Datetime"]).dt.tz_localize(None)
# set time zone and infer dst transition times
df["dt"] = df["dt"].dt.tz_localize("Europe/Amsterdam", ambiguous="infer")
df
Datetime Long Short dt
0 2022-10-30 02:00:00+02:00 61.58 61.58 2022-10-30 02:00:00+02:00
1 2022-10-30 02:15:00+02:00 49.98 49.98 2022-10-30 02:15:00+02:00
2 2022-10-30 02:30:00+02:00 26.72 26.72 2022-10-30 02:30:00+02:00
3 2022-10-30 02:45:00+02:00 -111.32 -111.32 2022-10-30 02:45:00+02:00
4 2022-10-30 02:00:00+02:00 -111.32 -111.32 2022-10-30 02:00:00+01:00
5 2022-10-30 02:15:00+02:00 -130.19 -130.19 2022-10-30 02:15:00+01:00
6 2022-10-30 02:30:00+02:00 -6.69 -6.69 2022-10-30 02:30:00+01:00
7 2022-10-30 02:45:00+02:00 -130.19 -130.19 2022-10-30 02:45:00+01:00
评论
0赞
ivar martens
10/9/2023
非常感谢!这确实解决了问题。
0赞
FObersteiner
10/10/2023
@ivarmartens很高兴您的问题得到了解决。您可能希望单击“接受为解决方案”按钮,以便其他人也知道;-)此外,这里要提到的一件事,可能并不总是正确的(只有当您的输入是“好的”时,情况似乎是这样) - 请记住这一点。ambiguous="infer"
评论