将包含时区的字符串转换为日期时间对象

Convert string with timezone included into datetime object

我有以下字符串格式: date = 'Jun 8, 2021 PDT' 我正在尝试将该字符串转换为 datetime 对象。现在我在:

dt_o = dt.strptime(date, '%b %d, %Y')

这几乎让我走到了尽头,但我仍然收到以下错误:

ValueError: unconverted data remains: PDT

有没有办法在 datetime 对象的原始创建中包含 'PDT'?。我的另一个选择是剥离 'PDT' 的字符串并创建一个时区未知对象。

dt_o = dt.strptime(date.rsplit(None, 1)[0], '%b %d, %Y') 给我一个对象:datetime.datetime(2021, 6, 8, 0, 0).

有什么方法可以应用 PDT 时区吗?我需要能够从字符串 date.rsplit(None, 1)[1] 转换它,因为它不会总是 PDT

你有没有检查文档?

dt_o = dt.strptime(date, '%b %d, %Y %Z')

一个常见的误解是 %Z 可以解析任意缩写的时区名称。这不可以。请特别参阅文档中 technical detail 下的“注释”部分#6。

您必须“手动”执行此操作,因为其中许多缩写词含糊不清。这是一个选项,如何仅使用标准库来处理它:

from datetime import datetime
from zoneinfo import ZoneInfo

# we need to define which abbreviation corresponds to which time zone
zoneMapping = {'PDT' : ZoneInfo('America/Los_Angeles'),
               'PST' : ZoneInfo('America/Los_Angeles'),
               'CET' : ZoneInfo('Europe/Berlin'),
               'CEST': ZoneInfo('Europe/Berlin')}

# some example inputs; last should fail
timestrings = ('Jun 8, 2021 PDT', 'Feb 8, 2021 PST', 'Feb 8, 2021 CET',
               'Aug 9, 2020 WTF')

for t in timestrings:
    # we can split off the time zone abbreviation
    s, z = t.rsplit(' ', 1)
    # parse the first part to datetime object
    # and set the time zone; use dict.get if it should be None if not found
    dt = datetime.strptime(s, "%b %d, %Y").replace(tzinfo=zoneMapping[z])
    print(t, "->", dt)

给予

Jun 8, 2021 PDT -> 2021-06-08 00:00:00-07:00
Feb 8, 2021 PST -> 2021-02-08 00:00:00-08:00
Feb 8, 2021 CET -> 2021-02-08 00:00:00+01:00

Traceback (most recent call last):

    dt = datetime.strptime(s, "%b %d, %Y").replace(tzinfo=zoneMapping[z])

KeyError: 'WTF'