Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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("
".join(sorted(names)))

Output

Asia/Calcutta
Asia/Colombo
Asia/Dacca
Asia/Dhaka
Asia/Karachi
Asia/Kathmandu
Asia/Katmandu
Asia/Kolkata
Asia/Thimbu
Asia/Thimphu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...