pandas
python
时区
看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gairuo123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
有以下数据,不过开始时间和结束时间为UTC时间,现在需要转换为北京时间。
# 将以下时间转换为北京时区
'''
start_time (UTC+0),end_time (UTC+0)
1,2020-08-03 23:50:27,2020-08-03 23:51:01
2,2020-08-03 11:02:27,2020-08-03 11:03:31
3,2020-08-01 12:17:48,2020-08-01 12:17:53
4,2020-08-01 12:08:58,2020-08-01 12:09:03
5,2020-08-03 04:29:22,2020-08-03 04:31:12
6,2020-08-03 03:43:07,2020-08-03 03:44:22
7,2020-08-01 12:16:08,2020-08-01 12:16:13
8,2020-07-31 22:35:36,2020-07-31 22:36:46
9,2020-08-01 13:48:55,2020-08-01 13:50:20
10,2020-08-02 14:11:08,2020-08-02 14:11:23
'''
首先,我们用剪贴板读取数据,然后对列改名,因为要修改为北京时间,就不能有UTC+0字样:
df.rename({'start_time(UTC+0)':'start_time',
'end_time(UTC+0)':'end_time'},
axis=1
)
# 或者以下方法
df.rename(lambda x:x.replace('(UTC+0)','') ,axis=1)
在转换时间之前要把数据的类型转换为时间类型,然后再操作时区转换,也可以用astype同时操作:
(
df.rename(lambda x:x.replace('(UTC+0)','') ,axis=1) # 修改列名
.astype('datetime64[ns, Asia/Shanghai]') # 时区转换
)
'''
start_time end_time
1 2020-08-03 23:50:27+08:00 2020-08-03 23:51:01+08:00
2 2020-08-03 11:02:27+08:00 2020-08-03 11:03:31+08:00
3 2020-08-01 12:17:48+08:00 2020-08-01 12:17:53+08:00
4 2020-08-01 12:08:58+08:00 2020-08-01 12:09:03+08:00
5 2020-08-03 04:29:22+08:00 2020-08-03 04:31:12+08:00
6 2020-08-03 03:43:07+08:00 2020-08-03 03:44:22+08:00
7 2020-08-01 12:16:08+08:00 2020-08-01 12:16:13+08:00
8 2020-07-31 22:35:36+08:00 2020-07-31 22:36:46+08:00
9 2020-08-01 13:48:55+08:00 2020-08-01 13:50:20+08:00
10 2020-08-02 14:11:08+08:00 2020-08-02 14:11:23+08:00
'''
就完成了时区转换的操作。在本例中,数据中的所有列为时间类型,如果在数据中只有指定的几列为时间,可以定义一个匿名函数来调用,以节省代码量:
df = df.rename(lambda x:x.replace('(UTC+0)','') ,axis=1) # 修改列名
to_utc8 = lambda x: x.astype('datetime64[ns, Asia/Shanghai]') # 定义函数
df.assign(start_time=to_utc8(df.start_time),
end_time=to_utc8(df.end_time))
(完)