![]() |
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 ZoneImporting necessary LibrariesPython3
Create Sample DataWe can convert a datetime object to the local time zone using the Python3
Output: DataFrame with UTC timestamps: 1. Converting to Local Time Zone using
|
# 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
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
Reffered: https://www.geeksforgeeks.org
AI ML DS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |