将日期时间字段转换为另一个时区并在 Python 中添加一个新列
Converting a Date Time Field to Another Time Zone and add a new colunm in Python
请告诉我如何将日期时间转换为另一个时区并在 Python 中添加一个新列。
我不太确定原始数据的确切时区(可能是 AEST),但我需要一个新的时间 - 比原来的时间(应该是加利福尼亚时间)17 小时。
喜欢这张图片:
https://i.stack.imgur.com/GCwUL.png
谢谢!
假设您有这样一个数据框:
time
0 1597101380360
1 1597099168350
2 1597095668690
3 1597085316180
4 1597054931440
而且您肯定知道时区是 'Australia/Queensland'
首先,让我们将时间转换为可读格式并将其保存在名为 date_time:
的新列中
df['date_time']= pd.to_datetime(pd.to_datetime(df.time, unit='ms',origin='unix'
).apply(lambda x: x.strftime("%Y-%m-%d %H:%M:%S")))
现在数据框看起来像这样:
time date_time
0 1597101380360 2020-08-10 23:16:20
1 1597099168350 2020-08-10 22:39:28
2 1597095668690 2020-08-10 21:41:08
3 1597085316180 2020-08-10 18:48:36
4 1597054931440 2020-08-10 10:22:11
现在,在我们更改时区之前,我们需要将 date_time 与创建时间戳的原始时区相关联,为此我们使用 tz_localize function. Then we create a new column called cali_time applying the function astimezone(timezone()) 将日期时间保存为新时区:
#assigning timezone to date_time
df['date_time']= df.date_time.dt.tz_localize('Australia/Queensland')
#creating new column with time zone set to US/Pacific
df['cali_time']=df.date_time.dt.tz_convert('US/Pacific')
df.head()
现在数据框看起来像这样:
time date_time cali_time
0 1597101380360 2020-08-10 23:16:20+10:00 2020-08-10 06:16:20-07:00
1 1597099168350 2020-08-10 22:39:28+10:00 2020-08-10 05:39:28-07:00
2 1597095668690 2020-08-10 21:41:08+10:00 2020-08-10 04:41:08-07:00
3 1597085316180 2020-08-10 18:48:36+10:00 2020-08-10 01:48:36-07:00
4 1597054931440 2020-08-10 10:22:11+10:00 2020-08-09 17:22:11-07:00
请告诉我如何将日期时间转换为另一个时区并在 Python 中添加一个新列。
我不太确定原始数据的确切时区(可能是 AEST),但我需要一个新的时间 - 比原来的时间(应该是加利福尼亚时间)17 小时。
喜欢这张图片:
https://i.stack.imgur.com/GCwUL.png
谢谢!
假设您有这样一个数据框:
time
0 1597101380360
1 1597099168350
2 1597095668690
3 1597085316180
4 1597054931440
而且您肯定知道时区是 'Australia/Queensland'
首先,让我们将时间转换为可读格式并将其保存在名为 date_time:
的新列中
df['date_time']= pd.to_datetime(pd.to_datetime(df.time, unit='ms',origin='unix'
).apply(lambda x: x.strftime("%Y-%m-%d %H:%M:%S")))
现在数据框看起来像这样:
time date_time
0 1597101380360 2020-08-10 23:16:20
1 1597099168350 2020-08-10 22:39:28
2 1597095668690 2020-08-10 21:41:08
3 1597085316180 2020-08-10 18:48:36
4 1597054931440 2020-08-10 10:22:11
现在,在我们更改时区之前,我们需要将 date_time 与创建时间戳的原始时区相关联,为此我们使用 tz_localize function. Then we create a new column called cali_time applying the function astimezone(timezone()) 将日期时间保存为新时区:
#assigning timezone to date_time
df['date_time']= df.date_time.dt.tz_localize('Australia/Queensland')
#creating new column with time zone set to US/Pacific
df['cali_time']=df.date_time.dt.tz_convert('US/Pacific')
df.head()
现在数据框看起来像这样:
time date_time cali_time
0 1597101380360 2020-08-10 23:16:20+10:00 2020-08-10 06:16:20-07:00
1 1597099168350 2020-08-10 22:39:28+10:00 2020-08-10 05:39:28-07:00
2 1597095668690 2020-08-10 21:41:08+10:00 2020-08-10 04:41:08-07:00
3 1597085316180 2020-08-10 18:48:36+10:00 2020-08-10 01:48:36-07:00
4 1597054931440 2020-08-10 10:22:11+10:00 2020-08-09 17:22:11-07:00