%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'