Home > Net >  How to convert UTC datetime to local datetime (Australia/Melbourne) in Python
How to convert UTC datetime to local datetime (Australia/Melbourne) in Python

Time:11-12

I have a data frame with "Date" column in UTC format.

Date
2021-10-14T06:57:00.000 0000
2021-09-05T08:30:00.000 0000
2021-10-20T04:34:00.000 0000
2021-10-19T21:49:00.000 0000
2021-09-30T20:53:00.000 0000

Tried this but didnt work;

df['Date'] = df['Date'].substr(replace(to_iso8601(from_iso8601_timestamp(Date) AT TIME ZONE 'Australia/Melbourne'), 'T', ' '), 1, 16) Date_local

I am unable to converte the UTC time to the local time zone (Australia/Melbourne).

Any help would be highly appreciated.

CodePudding user response:

use pandas functionality; pd.to_datetime and then tz_convert.

# input strings to datetime data type:
df['Date'] = pd.to_datetime(df['Date'])

# UTC is already set (aware datetime); just convert:
df['Date'] = df['Date'].dt.tz_convert('Australia/Melbourne')

df['Date']
Out[2]: 
0   2021-10-14 17:57:00 11:00
1   2021-09-05 18:30:00 10:00
2   2021-10-20 15:34:00 11:00
3   2021-10-20 08:49:00 11:00
4   2021-10-01 06:53:00 10:00
Name: Date, dtype: datetime64[ns, Australia/Melbourne]
  • Related