Calculate Time Difference Across Time Zones in Python
Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.
Python code
21 linesfrom datetime import datetime, timezone, timedelta
def time_difference(from_tz_offset, to_tz_offset):
"""
Calculate time difference in hours between two time zones given their offsets from UTC.
Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
"""
tz1 = timezone(timedelta(hours=from_tz_offset))
tz2 = timezone(timedelta(hours=to_tz_offset))
now = datetime.now(timezone.utc)
time1 = now.astimezone(tz1)
time2 = now.astimezone(tz2)
diff_hours = (time2.utcoffset().total_seconds() - time1.utcoffset().total_seconds()) / 3600
return diff_hours
if __name__ == "__main__":
# Example: EST (UTC-5) vs IST (UTC+5:30)
est_offset = -5
ist_offset = 5.5
diff = time_difference(est_offset, ist_offset)
print(f"Time difference between EST and IST: {diff} hours")
Output
Time difference between EST and IST: 10.5 hours
How it works
The function uses datetime.now(timezone.utc) to get the current UTC time, then converts it to each target time zone via astimezone(). The utcoffset() method returns the offset as a timedelta, and subtracting the seconds gives the exact hour difference. Because the code works entirely with the standard library's timezone and timedelta, it handles fractional hour offsets (like IST's UTC+5:30) correctly. The calculation is independent of daylight saving time when using fixed offsets, though real-world code should consider using pytz or zoneinfo for DST-aware zones.
Common mistakes
- Forgetting to call `total_seconds()` on the offset, which returns a `timedelta` not a number.
- Using `datetime.now(tz1)` directly without converting from UTC, leading to inconsistent base times.
- Assuming time zone offsets are always integers (e.g., 5.5 for IST) and not handling float precision.
- Mixing up the order of `from_tz_offset` and `to_tz_offset` when calculating the difference.
Variations
- Use `zoneinfo` (Python 3.9+) with IANA time zone names (e.g., 'America/New_York') instead of fixed offsets for DST support.
- Calculate the difference as a `timedelta` object and format it in hours:minutes:seconds.
Real-world use cases
- Scheduling international meetings by computing the time gap between team members in different cities.
- Converting timestamps in logs or events to a common reference for merging data across regional servers.
- Building a travel planner that shows time zone jumps when users book flights across continents.
Sponsored
Keep learning
Related tutorials and quizzes for this topic.