Hegde Avin
Hegde Avin

Reputation: 189

Getting timezone name from UTC offset

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.

Upvotes: 15

Views: 11383

Answers (1)

jfs
jfs

Reputation: 414215

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

Upvotes: 27

Related Questions