将数字偏移量转换为时区?

Convert numeric offset to a timezone?

有一个网站提供时区信息,例如-07:00。有没有一种方法可以使用它来本地化 pytz 中的时间戳?

通常我是这样做的:

EASTERN_TIMEZONE = pytz.timezone("US/Eastern")
date_in_pacific_time = EASTERN_TIMEZONE.localize(my_date)

其中 my_date 是某个 datetime 日期。但我不知道如何获取数字并从中获取时区,以便我可以将其应用于日期并从中获取时间戳。

虽然这可能是一个 XY 问题,因为我想做的是采用 "2021-04-02T18:30:04-07:00" 之类的日期字符串并将其转换为 Unix UTC 时间戳。

编辑:

像这样?

listing_date_string = "2021-04-02T18:30:04-07:00"
listing_date_string_datepart = listing_date_string[:19]
listing_date_string_timezone = int(listing_date_string[19:].replace(":00", ""))
d = datetime.datetime.strptime(listing_date_string_datepart, '%Y-%m-%dT%H:%M:%S')
d -= datetime.timedelta(hours=listing_date_string_timezone)

print(int(d.timestamp()))  # outputs 1617427804

X题,一般不可行。 但是你心里有一些候选时区,比如

  • US/Pacific
  • America/Phoenix
  • US/Mountain(与America/Denver相同)

所以你可以尝试每一个,看看它是否匹配 -7 小时。

有时候丹佛的时间是 -7 小时, 在其他日子里,洛杉矶是 -7 小时。 Phoenix 一直在 -7 小时

请注意,时区,如 US/Mountain,与时区偏移量(如 -7 小时)完全不同。

对于问题 Y,好吧,这很简单! 只需将第一部分视为 UTC, 然后应用剩余的 -7 小时校正。

这对你有用吗?

import datetime

dt = datetime.datetime.strptime(
    "2021-04-02T18:30:04-07:00", 
    "%Y-%m-%dT%H:%M:%S%z"
    )
print(
    dt.year,
    dt.month,
    dt.day,
    dt.hour,
    dt.minute,
    dt.second,
    dt.tzinfo,
    )
2021 4 2 18 30 4 UTC-07:00

Python < 3.7 - 来自 docs:

Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds.

反之亦然,这意味着对于旧的 Python 版本,%z 不会解析带有冒号的 UTC 偏移量作为 hours/minutes 分隔符。你可以像

这样解决
from datetime import datetime
# your input
s = "2021-04-02T18:30:04-07:00"
# parse separately, colon removed from UTC offset
tz = datetime.strptime(s[19:].replace(':', ''), '%z').tzinfo
dtobj = datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=tz)
print(repr(dtobj))
datetime.datetime(2021, 4, 2, 18, 30, 4, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))

如果您知道时区,则可以跳过解析 UTC 偏移量:

import pytz
tz = pytz.timezone('US/Pacific')
dtobj = tz.localize(datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S"))
print(repr(dtobj))
datetime.datetime(2021, 4, 2, 18, 30, 4, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)

注:标准库中pytz is deprecated with the release of Python 3.9 - you now have zoneinfo


Python 3.7+ 你可以只使用 fromisoformat;

dtobj = datetime.fromisoformat(s)

并从 UTC 偏移量更改为实际时区,如

dtobj.astimezone(tz) # tz is a timezone object from pytz, dateutil, zoneinfo...
Out[9]: datetime.datetime(2021, 4, 2, 18, 30, 4, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)