如何在python中计算两个时区之间的时差? [英] How to compute the time difference between two time zones in python?

查看:268
本文介绍了如何在python中计算两个时区之间的时差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中计算两个时区之间的时差?也就是说,我不想比较支持TZ的 datetime 对象并获得 timedelta ;我想比较两个 TimeZone 对象,并得到一个 offset_hours datetime 库中的任何内容都不能处理此问题, pytz

How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware datetime objects and get a timedelta; I want to compare two TimeZone objects and get an offset_hours. Nothing in the datetime library handles this, and neither does pytz.

推荐答案

您必须知道的第一件事是两个时区之间的偏移量不仅取决于相关的时区,还取决于您询问的日期。例如,夏令时的开始和结束日期在2007年在美国发生了变化。基本时区的物流仅在任何一个地点很少发生变化,而全球的变化率却不可忽视。因此,必须将有问题的日期合并到函数中。

The first thing you have to know is that the offset between two time zones depends not only on the time zones in question, but on the date you're asking about. For example, the dates on which Daylight Savings Time began and ended changed in the US in 2007. While fundamental time zone logistics change only infrequently in any single location, the rate of change globally is impossible to ignore. Therefore, you have to incorporate the date in question into your function.

已完成必要的序言,如果您充分利用了实际的函数,就不会太难写钟摆库。它应该看起来像这样:

Having completed the necessary preface, the actual function isn't too hard to write if you take advantage of the pendulum library. It should look something like this:

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

如文档中所述,在一年中的每一天中,您可能都无法在两个给定位置之间获得稳定的结果。选择当年中位数结果的变体是留给读者的练习。

As stated in the documentation, you may not get a stable result for this between any two given locations as you sweep across the days of the year. However, implementing a variant which chooses the median result over the days of the current year is an exercise left for the reader.

这篇关于如何在python中计算两个时区之间的时差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆