Convert Datetime Object To Local Time Zone In Pandas
Last Updated :
08 Feb, 2024
Pandas has established itself as one of the most powerful and versatile libraries in Python. When working with time series data, handling datetime objects efficiently becomes paramount. Oftentimes, datasets contain timestamps in various time zones, necessitating conversion to a consistent reference point, typically the local time zone
Convert Datetime Object To Local Time Zone
Importing necessary Libraries
Python3
import pandas as pd
from datetime import datetime
import pytz
|
Create Sample Data
We can convert a datetime object to the local time zone using the datetime
and pytz
modules
Python3
data = {
'timestamp_utc' : [
'2024-02-07 08:00:00' ,
'2024-02-07 12:00:00' ,
'2024-02-07 16:00:00'
]
}
df = pd.DataFrame(data)
df[ 'timestamp_utc' ] = pd.to_datetime(df[ 'timestamp_utc' ])
print ( "DataFrame with UTC timestamps:" )
print (df)
|
Output:
DataFrame with UTC timestamps:
timestamp_utc
0 2024-02-07 08:00:00
1 2024-02-07 12:00:00
2 2024-02-07 16:00:00
1. Converting to Local Time Zone using pytz.timezone()
The local time zone ‘Asia/Kolkata’ is assigned using the pytz.timezone()
function, representing the Indian Standard Time (IST),
Python3
local_timezone = pytz.timezone( 'America/New_York' )
df[ 'timestamp_local' ] = df[ 'timestamp_utc' ].dt.tz_localize( 'UTC' ).dt.tz_convert(local_timezone)
print ( "\nDataFrame with local time zone:" )
print (df)
|
Output:
DataFrame with local time zone:
timestamp_utc timestamp_local
0 2024-02-07 08:00:00 2024-02-07 03:00:00-05:00
1 2024-02-07 12:00:00 2024-02-07 07:00:00-05:00
2 2024-02-07 16:00:00 2024-02-07 11:00:00-05:00
2. Converting to Local Time Zone using tz_convert()
We will implement conversion to Local Time using tz_convert().
Python3
df[ 'timestamp_local' ] = df[ 'timestamp_utc' ].dt.tz_localize( 'UTC' )
df[ 'timestamp_local' ] = df[ 'timestamp_local' ].dt.tz_convert( 'Asia/Kolkata' )
print ( "\nDataFrame with local time zone (Asia/Kolkata):" )
print (df)
|
Output:
DataFrame with local time zone (Asia/Kolkata):
timestamp_utc timestamp_local
0 2024-02-07 08:00:00 2024-02-07 13:30:00+05:30
1 2024-02-07 12:00:00 2024-02-07 17:30:00+05:30
2 2024-02-07 16:00:00 2024-02-07 21:30:00+05:30
Share your thoughts in the comments
Please Login to comment...