Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytz Timezone from UTC offset

I'm using Facebook's graph API with Python. For any user_id, it gives the timezone of the user as a float which represents the offset from UTC.

Example: For someone in India, it gives 5.5

How would I convert this into a valid timezone like Asia/Kolkata?

I've looked into pytz but didn't find any suitable ways to do it.

like image 635
Pattu Avatar asked Sep 04 '17 12:09

Pattu


People also ask

What is pytz timezone?

The pytz module allows for date-time conversion and timezone calculations so that your Python applications can keep track of dates and times, while staying accurate to the timezone of a particular location.

How do you calculate UTC offset?

(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.

Does pytz handle DST?

pytz will help you to tell if an date is under DST influence by checking dst() method.

How do I set UTC time zone in Python?

Use pytz. timezone() and datetime. tzinfo. localize() to set the timezone of a datetime.


1 Answers

You can find all of time zones that match a given offset (ignoring DST) for the last entry in the Olson database by looking at all entries.

Code:

import datetime as dt
import pytz

def possible_timezones(tz_offset, common_only=True):
    # pick one of the timezone collections
    timezones = pytz.common_timezones if common_only else pytz.all_timezones

    # convert the float hours offset to a timedelta
    offset_days, offset_seconds = 0, int(tz_offset * 3600)
    if offset_seconds < 0:
        offset_days = -1
        offset_seconds += 24 * 3600
    desired_delta = dt.timedelta(offset_days, offset_seconds)

    # Loop through the timezones and find any with matching offsets
    null_delta = dt.timedelta(0, 0)
    results = []
    for tz_name in timezones:
        tz = pytz.timezone(tz_name)
        non_dst_offset = getattr(tz, '_transition_info', [[null_delta]])[-1]
        if desired_delta == non_dst_offset[0]:
            results.append(tz_name)

    return results

Test Code:

print(possible_timezones(5.5, common_only=False))

Results:

['Asia/Calcutta', 'Asia/Colombo', 'Asia/Kolkata']
like image 147
Stephen Rauch Avatar answered Sep 22 '22 15:09

Stephen Rauch