Timezones help us understand when events happen in different parts of the world. Handling timezones correctly avoids confusion in time data.
0
0
Timezone handling basics in Pandas
Introduction
You have timestamps from users in different countries and want to compare them.
You want to convert event times from one timezone to another.
You need to store times in a standard timezone like UTC for consistency.
You want to display times in the local timezone of your audience.
You are analyzing data collected across multiple timezones.
Syntax
Pandas
import pandas as pd dt = pd.Timestamp('2024-06-01 12:00') # Create timezone-aware datetime pd.Timestamp('2024-06-01 12:00').tz_localize('America/New_York') # Convert timezone dt.tz_convert('Europe/London')
tz_localize sets the timezone for naive timestamps (no timezone info).
tz_convert changes the timezone of an aware timestamp.
Examples
Make a naive timestamp timezone-aware by setting it to UTC.
Pandas
import pandas as pd dt = pd.Timestamp('2024-06-01 12:00') dt_aware = dt.tz_localize('UTC') print(dt_aware)
Convert the UTC time to New York time.
Pandas
dt_ny = dt_aware.tz_convert('America/New_York') print(dt_ny)
Create a New York time and convert it to UTC.
Pandas
dt_ny = pd.Timestamp('2024-06-01 08:00').tz_localize('America/New_York') dt_utc = dt_ny.tz_convert('UTC') print(dt_utc)
Sample Program
This program shows how to start with a time without timezone, add UTC timezone, then convert it to Tokyo and New York times.
Pandas
import pandas as pd # Create a naive timestamp naive_time = pd.Timestamp('2024-06-01 15:00') print(f"Naive time: {naive_time}") # Localize to UTC timezone utc_time = naive_time.tz_localize('UTC') print(f"UTC time: {utc_time}") # Convert UTC time to Tokyo timezone tokyo_time = utc_time.tz_convert('Asia/Tokyo') print(f"Tokyo time: {tokyo_time}") # Convert UTC time to New York timezone ny_time = utc_time.tz_convert('America/New_York') print(f"New York time: {ny_time}")
OutputSuccess
Important Notes
Always localize naive timestamps before converting timezones.
Timezone names like 'America/New_York' follow the IANA timezone database.
UTC is a good standard timezone to store times before converting to local zones.
Summary
Timezone handling avoids confusion when working with times from different places.
Use tz_localize to add timezone info to naive timestamps.
Use tz_convert to change the timezone of aware timestamps.