在Pandas DataFrame中组合日期时间和时区列(tz_localize from column)



如前所述(转换时区pandas数据帧(,pandas提供了本地化datetime列(tz_localize(和将时区(tz_convert(转换为预定义时区的方法。例如:

df["localized_time"] = df.time.tz_localize(pytz.utc).tz_convert("Some/Timezone")

但是,这两个函数都接受时区本身作为参数。如果时区来自同一数据帧中的另一列,该怎么办?例如:

time                 timezone        ...
0  2022-04-11 12:24:43  "Europe/Paris"  ...
1  2022-04-11 04:22:12  "US/Eastern"    ...
...

有没有一种简单的方法可以将";时间";列(已经是datetime类型(,其中时区取"0";"时区";列(字符串(?

是的,这是可能的,例如:

df["localized_time"] = df.time.dt.tz_localize(pytz.utc)
df['new'] = df.apply(lambda x: x["localized_time"].tz_convert(x["timezone"]), 1)
print (df)
time      timezone            localized_time  
0 2022-04-11 12:24:43  Europe/Paris 2022-04-11 12:24:43+00:00   
1 2022-04-11 04:22:12    US/Eastern 2022-04-11 04:22:12+00:00   
new  
0  2022-04-11 14:24:43+02:00  
1  2022-04-11 00:22:12-04:00 

但因为有不同的时区,所以得到objects而不是datetimesdtype:

print (df.dtypes)
time                   datetime64[ns]
timezone                       object
localized_time    datetime64[ns, UTC]
new                            object
dtype: object

最新更新