Pytz时区从UTC偏移量

10
我正在使用Python的Facebook图谱API。对于任何user_id,它都会给出用户所在时区的浮点数,该数表示相对于世界标准时间的偏移量。
例如:对于印度的某个人,它会给出5.5。
我该如何将其转换为有效的timezone,如Asia/Kolkata
我已经研究了pytz,但没有找到合适的方法来执行此操作。

3
除非你也知道位置,否则这句话就没什么意义了——因为大多数偏移量都对应多个时区。 - CBroe
2
可能存在多个使用相同偏移量的时区。最好的方法是获取一个可能的时区列表:https://dev59.com/p6Lia4cB1Zd3GeqPrfgo#44811038 - user7605325
2
我知道。但这是一个我可以接受的缺点。 - Pattu
1个回答

16

通过查看所有条目,您可以找到与给定偏移量(忽略DST)匹配的所有时区,以获得Olson数据库中的最后一个条目。

代码:

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

测试代码:

print(possible_timezones(5.5, common_only=False))

结果:

['Asia/Calcutta', 'Asia/Colombo', 'Asia/Kolkata']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接