2017-10-13 154 views

回答

4

您必須知道的第一件事是兩個時區之間的偏移量不僅取決於有問題的時區,而且取決於您詢問的日期。例如,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 

如文檔中所述,您可能無法獲得穩定的結果,這是您在一年中的天掃任何兩個給定位置之間。然而,實施一個在當年的日子裏選擇中位數結果的變量是爲讀者留下的練習。

相關問題