【问题标题】:Pytz Timezone from UTC offset来自 UTC 偏移的 Pytz 时区
【发布时间】:2018-02-12 16:31:38
【问题描述】:

我在 Python 中使用 Facebook 的图形 API。对于任何user_id,它将用户的时区作为一个浮点数给出,表示与UTC的偏移量。

示例:对于印度的某人,它给出 5.5

如何将其转换为有效的timezone,例如Asia/Kolkata

我查看了pytz,但没有找到任何合适的方法。

【问题讨论】:

  • 除非您也有位置,否则这没有什么意义 - 对于大多数偏移量来说,有多个时区。
  • 可以有多个时区使用相同的偏移量。您能做的最好的事情就是获取可能的时区列表stackoverflow.com/a/44811038/7605325
  • 我知道。但这是我可以忍受的缺点。

标签: python datetime facebook-graph-api timezone pytz


【解决方案1】:

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

代码:

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']

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 2015-02-14
    • 2019-04-08
    • 2015-07-20
    • 2011-12-25
    • 2021-06-04
    • 2016-08-24
    • 1970-01-01
    • 2014-02-04
    相关资源
    最近更新 更多