将其他时区转换为本地时区(偏移量)

Converting other time zones into local time zone (offset)

我正在尝试创建一个将两个参数作为输入的函数。

  1. 字符串形式的时间 ("2021-08-13 19:00")
  2. 时区(-4)

我想要函数将给定时区的时间转换为我计算机的本地时区(偏移量)。有人可以帮忙吗?

您可以创建 timezone object from the UTC offset hours via a timedelta object. Then use tzlocal to obtain the local time zone (i.e. the one your machine is configured to use) and convert using astimezone

例如:

from datetime import datetime, timedelta, timezone
from tzlocal import get_localzone # pip install tzlocal

def to_local(s, offsethours):
    """
    convert date/time string plus UTC offset hours to date/time in
    local time zone.
    """
    dt = datetime.fromisoformat(s).replace(tzinfo=timezone(timedelta(hours=offsethours)))
    # for Python < 3.7, use datetime.strptime(s, "%Y-%m-%d %H:%M") instead of datetime.fromisoformat(s)
    return dt.astimezone(get_localzone())
    
    
time_string = "2021-08-13 19:00"
time_offset = -4

dt_local = to_local(time_string, time_offset)

print(repr(dt_local))
print(dt_local.isoformat())
print(dt_local.utcoffset())
# datetime.datetime(2021, 8, 14, 1, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
# 2021-08-14T01:00:00+02:00
# 2:00:00