Reputation: 15
Please show me how to convert a Date Time to Another Time Zone and add a new colunm in Python.
I am not very sure about the exact timezone of the original data (Maybe is AEST) but I need a new coulmn that is - 17 Hours than the original one (should be California time).
Like this picture:
https://i.sstatic.net/GCwUL.png
Thank you!
Upvotes: 0
Views: 121
Reputation: 331
Let's say that you have a dataframe like this:
time
0 1597101380360
1 1597099168350
2 1597095668690
3 1597085316180
4 1597054931440
And you know for sure that the time zone is 'Australia/Queensland'
First, let's get the time converted to a readable format and save it in a new column called 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")))
Now the dataframe looks like this:
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
Now, before we change the timezone, we need to associate the date_time with the original timezone the timestamp was created, for that we use the tz_localize function. Then we create a new column called cali_time applying the function astimezone(timezone()) to save the datetime with the new 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()
Now the dataframe looks like this:
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
Upvotes: 2