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 - Get the UTC Offset Time
To get the UTC offset time in Pandas, use the timestamp.utcoffset() method. The UTC offset represents the time difference between a timezone and Coordinated Universal Time (UTC).
What is UTC Offset?
UTC offset shows how many hours a timezone is ahead or behind UTC. For example, EST is UTC-5, while IST is UTC+5:30.
Basic Usage
First, let's create a timestamp and get its UTC offset ?
import pandas as pd
# Creating a timestamp with UTC timezone
timestamp = pd.Timestamp('2021-10-16T15:12:34.261811624', tz='UTC')
print("Timestamp:", timestamp)
# Get the UTC offset time
offset = timestamp.utcoffset()
print("UTC offset:", offset)
Timestamp: 2021-10-16 15:12:34.261811624+00:00 UTC offset: 0:00:00
UTC Offset with Different Timezones
Let's see how UTC offset works with various timezones ?
import pandas as pd
# Different timezone examples
timezones = ['UTC', 'US/Eastern', 'Asia/Kolkata', 'Europe/London']
for tz in timezones:
timestamp = pd.Timestamp('2021-10-16T15:12:34', tz=tz)
offset = timestamp.utcoffset()
print(f"{tz}: {offset}")
UTC: 0:00:00 US/Eastern: -1 days +20:00:00 Asia/Kolkata: 5:30:00 Europe/London: 1:00:00
Converting to Hours
You can convert the offset to hours for easier interpretation ?
import pandas as pd
timestamp = pd.Timestamp('2021-10-16T15:12:34', tz='Asia/Kolkata')
offset = timestamp.utcoffset()
# Convert to hours
offset_hours = offset.total_seconds() / 3600
print(f"UTC offset: {offset}")
print(f"Offset in hours: {offset_hours}")
UTC offset: 5:30:00 Offset in hours: 5.5
Practical Example
Here's how to work with multiple timestamps and their UTC offsets ?
import pandas as pd
# Create timestamps in different timezones
timestamps = [
pd.Timestamp('2021-10-16T15:12:34', tz='UTC'),
pd.Timestamp('2021-10-16T15:12:34', tz='US/Pacific'),
pd.Timestamp('2021-10-16T15:12:34', tz='Asia/Tokyo')
]
for ts in timestamps:
print(f"Time: {ts}")
print(f"UTC Offset: {ts.utcoffset()}")
print("---")
Time: 2021-10-16 15:12:34+00:00 UTC Offset: 0:00:00 --- Time: 2021-10-16 15:12:34-07:00 UTC Offset: -1 days +17:00:00 --- Time: 2021-10-16 15:12:34+09:00 UTC Offset: 9:00:00 ---
Conclusion
The utcoffset() method returns the timezone's offset from UTC as a timedelta object. Use total_seconds() / 3600 to convert the offset to hours for easier interpretation.
