15

How can I get the timezone name from a given UTC offset in Python?

For example, I have,

"GMT+0530"

And I want to get,

"Asia/Calcutta"

If there are multiple matches, the result should be a list of timezone names.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Hegde Avin
  • 189
  • 1
  • 1
  • 8
  • 4
    1. What have you tried? 2. What if it isn't a one-to-one mapping? – jonrsharpe Jan 29 '16 at 13:09
  • Possible duplicate of [How can I get a human-readable timezone name in Python?](http://stackoverflow.com/questions/3489183/how-can-i-get-a-human-readable-timezone-name-in-python) – Fabian Fagerholm Jan 29 '16 at 13:50
  • related: [Get timezone abbreviation from UTC offset](http://stackoverflow.com/q/19251420/4279). Use `tz.zone` instead of `tzname()` in [this answer](http://stackoverflow.com/a/30139320/4279) – jfs Jan 29 '16 at 13:54
  • 1
    See also "Time Zone != Offset" in the [timezone tag wiki](https://stackoverflow.com/tags/timezone/info). – Matt Johnson-Pint Sep 14 '18 at 17:22

1 Answers1

28

There could be zero or more (multiple) timezones that correspond to a single UTC offset. To find these timezones that have a given UTC offset now:

#!/usr/bin/env python
from datetime import datetime, timedelta
import pytz  # $ pip install pytz

utc_offset = timedelta(hours=5, minutes=30)  # +5:30
now = datetime.now(pytz.utc)  # current time
print({tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set)
       if now.astimezone(tz).utcoffset() == utc_offset})

Output

set(['Asia/Colombo', 'Asia/Calcutta', 'Asia/Kolkata'])

If you want to take historical data into account (timezones that had/will have a given utc offset at some date according to the current time zone rules):

#!/usr/bin/env python
from datetime import datetime, timedelta
import pytz  # $ pip install pytz

utc_offset = timedelta(hours=5, minutes=30)  # +5:30
names = set()
now = datetime.now(pytz.utc)
for tz in map(pytz.timezone, pytz.all_timezones_set):
    dt = now.astimezone(tz)
    tzinfos = getattr(tz, '_tzinfos',
                      [(dt.utcoffset(), dt.dst(), dt.tzname())])
    if any(off == utc_offset for off, _, _ in tzinfos):
        names.add(tz.zone)
print("\n".join(sorted(names)))

Output

Asia/Calcutta
Asia/Colombo
Asia/Dacca
Asia/Dhaka
Asia/Karachi
Asia/Kathmandu
Asia/Katmandu
Asia/Kolkata
Asia/Thimbu
Asia/Thimphu
jfs
  • 399,953
  • 195
  • 994
  • 1,670