如何计算python中两个时区之间的时差?

时间:2017-10-13 19:05:14

标签: python datetime timezone

如何计算Python中两个时区之间的时差?也就是说,我不想比较TZ感知的datetime个对象并获得timedelta;我想比较两个TimeZone个对象并获得offset_hoursdatetime库中没有任何内容可以处理此问题,pytz也没有。

7 个答案:

答案 0 :(得分:8)

您必须要知道的第一件事是两个时区之间的偏移不仅取决于所讨论的时区,还取决于您询问的日期。例如,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

正如文档中所述,当您横扫一年中的任何一天时,您可能无法在任何两个给定位置之间获得稳定的结果。但是,实施一个在当年选择中位数结果的变体是留给读者的一个练习。

答案 1 :(得分:0)

下面是一个代码片段,用于了解UTC和美国/东部之间的差异,但它应适用于任何两个时区。

# The following algorithm will work no matter what is the local timezone of the server,
# but for the purposes of this discussion, let's assume that the local timezone is UTC.
local_timestamp = datetime.now()
# Assume that utc_timestamp == 2019-01-01 12:00.
utc_timestamp = pytz.utc.localize(local_timestamp)
# If it was 12:00 in New York, it would be 20:00 in UTC. So us_eastern_timestamp is a UTC
# timestamp with the value of 2019-01-01 20:00.
us_eastern_timestamp = timezone("US/Eastern").localize(local_timestamp).astimezone(pytz.utc)
# delta is a Python timedelta object representing the interval between the two timestamps,
# which, in our example, is -8 hours.
delta = utc_timestamp - us_eastern_timestamp
# In the last line, we convert the timedelta into an integer representing the number of
# hours.
print round(delta.total_seconds() / 60.0 / 60.0)

答案 2 :(得分:0)

这是另一种解决方案:

from datetime import datetime
from pytz import timezone
from dateutil.relativedelta import relativedelta

utcnow = timezone('utc').localize(datetime.utcnow()) # generic time
here = utcnow.astimezone(timezone('US/Eastern')).replace(tzinfo=None)
there = utcnow.astimezone(timezone('Asia/Ho_Chi_Minh')).replace(tzinfo=None)

offset = relativedelta(here, there) 
offset.hours

在这里,我们正在做的是将时间转换为两个不同的时区。然后,我们删除时区信息,以便在您使用relativedelta计算两者之间的差异时,使我们误以为这是时间上的两个不同时刻,而不是不同时区中的相同时刻。

以上结果将返回-11,但是由于美国/东部遵守DST而亚洲/ Ho_Chi_Minh并未遵守DST,因此该金额可能会全年变化。

答案 3 :(得分:0)

dict_1 = {'user': username, 'areas': {new_profile.get('areas') for x in new_profs}}

其中tz_from和tz_to是开始和结束时区。您必须指定一个特定日期。

答案 4 :(得分:0)

我创建了两个函数来处理时区。

np.repeat(...)

我希望它会有所帮助!

答案 5 :(得分:0)

这是使用Python库Pytz的解决方案,它解决了夏时制结束时时间模糊的问题。


from pytz import timezone
import pandas as pd

def tz_diff(date, tz1, tz2):
    '''
    Returns the difference in hours between timezone1 and timezone2
    for a given date.
    '''
    date = pd.to_datetime(date)
    return (tz1.localize(date) - 
            tz2.localize(date).astimezone(tz1))\
            .seconds/3600

以下示例分别计算1月1日和6月1日UTC与澳大利亚时间之间的小时差。请注意如何考虑夏令时。

utc = timezone('UTC')
aus = timezone('Australia/Sydney')

tz_diff('2017-01-01', utc, aus)

# 11.0

tz_diff('2017-06-01', utc, aus)

# 10.0

谢谢

答案 6 :(得分:0)

from datetime import datetime
from zoneinfo import ZoneInfo

dt = datetime.now() # 2020-09-13
tz0, tz1 = "Europe/Berlin", "US/Eastern" # +2 vs. -4 hours rel. to UTC

utcoff0, utcoff1 = dt.astimezone(ZoneInfo(tz0)).utcoffset(), dt.astimezone(ZoneInfo(tz1)).utcoffset()

print(f"hours offset between {tz0} -> {tz1} timezones: {(utcoff1-utcoff0).total_seconds()/3600}")
>>> hours offset between Europe/Berlin -> US/Eastern timezones: -6.0
  • 使用 Python 3.9 的标准库进行此操作的方法。