santiagobasulto
santiagobasulto

Reputation: 11686

How to pick a timezone based on UTC offset?

i've got a silly problem. I'm parsing Facebook user data, and I get the timezone as a number:

timezone: The user's timezone offset from UTC

For me ('America/Argentina/Buenos_Aires') it's -3.

Now, how can I convert that number to a pytz.timezone?

Thank you!

Upvotes: 4

Views: 4770

Answers (3)

jfs
jfs

Reputation: 414215

As @Mark Ransom said, multiple pytz.timezone may have the same UTC offset at a given date. You could print the mapping for a particular date:

#!/usr/bin/env python
from collections import defaultdict
from datetime import datetime

import pytz # $ pip install pytz

dt = datetime.now(pytz.utc) # current time in UTC
zone_names = defaultdict(list)
for tz in pytz.common_timezones:
    zone_names[dt.astimezone(pytz.timezone(tz)).utcoffset()].append(tz)

for offset, zone in sorted(zone_names.items()):
    print("%.1f %s" % (offset.total_seconds() / 3600, zone))
# -> -11.0 ['Pacific/Midway', 'Pacific/Niue', 'Pacific/Pago_Pago']
# ...

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308158

There's not a 1:1 correspondence, so there's no way to do it without making some assumptions that are bound to be invalid.

You can create your own tzinfo class that encodes the offset directly without trying to tie it back to a zone.

Upvotes: 6

0xd
0xd

Reputation: 1901

You can use tzinfo.tzname to get the zone name.

Upvotes: -3

Related Questions