如何计算python中两个时区之间的时差?
问题描述:
如何计算Python中两个时区之间的时差?也就是说,我不想比较TZ-aware datetime
对象并获得timedelta
;我想比较两个TimeZone
对象并获得offset_hours
。 datetime
库中没有任何内容处理这个问题,pytz
也没有。如何计算python中两个时区之间的时差?
答
您必须知道的第一件事是两个时区之间的偏移量不仅取决于有问题的时区,而且取决于您询问的日期。例如,2007年美国夏令时开始和结束的日期发生了变化。虽然基本时区物流在任何一个地点都不会发生变化,但全球范围内的变化速度是不可忽视的。因此,您必须将相关日期并入您的函数中。
完成必要的前言后,如果利用pendulum库,实际功能不会太难编写。它应该是这个样子:
import pendulum
def tz_diff(home, away, on=None):
"""
Return the difference in hours between the away time zone and home.
`home` and `away` may be any values which pendulum parses as timezones.
However, recommended use is to specify the full formal name.
See https://gist.github.com/pamelafox/986163
As not all time zones are separated by an integer number of hours, this
function returns a float.
As time zones are political entities, their definitions can change over time.
This is complicated by the fact that daylight savings time does not start
and end on the same days uniformly across the globe. This means that there are
certain days of the year when the returned value between `Europe/Berlin` and
`America/New_York` is _not_ `6.0`.
By default, this function always assumes that you want the current
definition. If you prefer to specify, set `on` to the date of your choice.
It should be a `Pendulum` object.
This function returns the number of hours which must be added to the home time
in order to get the away time. For example,
```python
>>> tz_diff('Europe/Berlin', 'America/New_York')
-6.0
>>> tz_diff('Europe/Berlin', 'Asia/Kabul')
2.5
```
"""
if on is None:
on = pendulum.today()
diff = (on.timezone_(home) - on.timezone_(away)).total_hours()
# what about the diff from Tokyo to Honolulu? Right now the result is -19.0
# it should be 5.0; Honolulu is naturally east of Tokyo, just not so around
# the date line
if abs(diff) > 12.0:
if diff < 0.0:
diff += 24.0
else:
diff -= 24.0
return diff
如文档中所述,您可能无法获得稳定的结果,这是您在一年中的天扫任何两个给定位置之间。然而,实施一个在当年的日子里选择中位数结果的变量是为读者留下的练习。