在 pytz 中提取时区偏移量的更优雅的方法是什么?
What is a more elegant way of extracting timezone offsets in pytz?
我有一些代码使用 datetime
、pytz
和 re
来确定给定时区的 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 似乎很浪费。
我们怎样才能使这段代码更好?
如果您查看 documentation for Python tzinfo
objects,您会看到一个名为 utcoffset
的方法。这将直接为您提供偏移量。
delta = tzone.utcoffset(that_day)
return delta
编辑:无需在 datetime
上调用 localize
,pytz
对象作为 utcoffset
的一部分自行完成。它希望传递一个简单的日期时间。
我有一些代码使用 datetime
、pytz
和 re
来确定给定时区的 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 似乎很浪费。
我们怎样才能使这段代码更好?
如果您查看 documentation for Python tzinfo
objects,您会看到一个名为 utcoffset
的方法。这将直接为您提供偏移量。
delta = tzone.utcoffset(that_day)
return delta
编辑:无需在 datetime
上调用 localize
,pytz
对象作为 utcoffset
的一部分自行完成。它希望传递一个简单的日期时间。