Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - Convert Timestamp to another time zone
Converting timestamps between time zones is essential when working with global data. Pandas provides the tz_convert() method to easily convert timezone-aware timestamps to different time zones.
Import Required Libraries
First, import the pandas library ?
import pandas as pd
Creating a Timezone-Aware Timestamp
Create a timestamp object with an initial timezone. The timezone parameter accepts standard timezone names ?
import pandas as pd
# Create timestamp with US/Eastern timezone
timestamp = pd.Timestamp('2021-10-14T15:12:34.261811624', tz='US/Eastern')
print("Original timestamp:", timestamp)
Original timestamp: 2021-10-14 15:12:34.261811624-04:00
Converting to Another Time Zone
Use the tz_convert() method to convert the timestamp to a different timezone ?
import pandas as pd
timestamp = pd.Timestamp('2021-10-14T15:12:34.261811624', tz='US/Eastern')
# Convert to Australia/Brisbane timezone
converted_timestamp = timestamp.tz_convert('Australia/Brisbane')
print("Converted timestamp:", converted_timestamp)
Converted timestamp: 2021-10-15 05:12:34.261811624+10:00
Complete Example
Here's a comprehensive example showing timezone conversion ?
import pandas as pd
# Create timestamp with US/Eastern timezone
timestamp = pd.Timestamp('2021-10-14T15:12:34.261811624', tz='US/Eastern')
# Display the original timestamp
print("Original Timestamp:")
print(timestamp)
# Convert to different timezones
print("\nConverted to Australia/Brisbane:")
print(timestamp.tz_convert('Australia/Brisbane'))
print("\nConverted to Europe/London:")
print(timestamp.tz_convert('Europe/London'))
print("\nConverted to Asia/Tokyo:")
print(timestamp.tz_convert('Asia/Tokyo'))
Original Timestamp: 2021-10-14 15:12:34.261811624-04:00 Converted to Australia/Brisbane: 2021-10-15 05:12:34.261811624+10:00 Converted to Europe/London: 2021-10-14 20:12:34.261811624+01:00 Converted to Asia/Tokyo: 2021-10-15 04:12:34.261811624+09:00
Key Points
- The timestamp must be timezone-aware before using
tz_convert() - Use standard timezone names like 'US/Eastern', 'Europe/London', 'Asia/Tokyo'
- The method returns a new timestamp object with the converted timezone
- The actual moment in time remains the same, only the timezone representation changes
Conclusion
The tz_convert() method provides a simple way to convert timezone-aware timestamps between different time zones. This is particularly useful when working with data from multiple geographical locations or when standardizing timestamps for analysis.
