【问题标题】:What is a more elegant way of extracting timezone offsets in pytz?在 pytz 中提取时区偏移的更优雅的方法是什么?
【发布时间】:2019-05-05 09:21:22
【问题描述】:

我有一段代码使用datetimepytzre 来确定给定时区的UTC 偏移量,形式为datetime.timedelta 对象:

def get_utcoffset(mic, date):
    that_day = datetime.datetime.combine(date, datetime.time())
    tzone = pytz.timezone(timezones[mic]) # e.g. pytz.timezone("Asia/Tokyo")
    offset_string = tzone.localize(that_day).strftime("%z")
    pattern = "^(.)(\\d{2})(\\d{2})$"
    captured = re.search(pattern, offset_string)
    sign = captured.group(1)
    hh = int(captured.group(2))
    mm = int(captured.group(3))
    if sign == "-":
        return datetime.timedelta(hours=-hh, minutes=-mm)
    return datetime.timedelta(hours=hh, minutes=mm)

看起来应该有一种更优雅、更有效的方法来做到这一点,因为pytz.timezone.localize 必须知道它自己相对于 UTC 的偏移量。将偏移值提取为字符串然后使用正则表达式基本上对字符串进行 sscanf 似乎很浪费。

我们怎样才能使这段代码更好?

【问题讨论】:

    标签: python timezone pytz


    【解决方案1】:

    如果您查看documentation for Python tzinfo objects,您会看到一个名为utcoffset 的方法。这将直接为您提供偏移量。

    delta = tzone.utcoffset(that_day)
    return delta
    

    编辑:无需在datetime 上调用localizepytz 对象本身作为utcoffset 的一部分。它期望传递一个简单的日期时间。

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2018-02-12
      • 2019-11-22
      • 2015-07-20
      • 2019-09-26
      • 2011-11-12
      • 2020-10-11
      • 2011-03-27
      • 1970-01-01
      相关资源
      最近更新 更多