Open In App

Convert Datetime Object To Local Time Zone In Pandas

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




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






# Create a sample DataFrame with datetime columns
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'])
 
# Display the DataFrame
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),






# Convert UTC timestamps to local time zone
local_timezone = pytz.timezone('America/New_York'# Example: Convert to New York time zone
 
df['timestamp_local'] = df['timestamp_utc'].dt.tz_localize('UTC').dt.tz_convert(local_timezone)
 
# Display the DataFrame with local time zone
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().




# Localize UTC timestamps to UTC time zone
df['timestamp_local'] = df['timestamp_utc'].dt.tz_localize('UTC')
 
# Convert localized timestamps to local time zone (Asia/Kolkata)
df['timestamp_local'] = df['timestamp_local'].dt.tz_convert('Asia/Kolkata')
 
# Display the DataFrame with local time zone
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


Article Tags :