【问题标题】:Convert string with timezone included into datetime object将包含时区的字符串转换为日期时间对象
【发布时间】:2021-08-24 18:51:45
【问题描述】:

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

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

这让我几乎一直到那里,但我仍然收到以下错误:

ValueError:未转换的数据仍然存在:PDT

有没有办法将'PDT' 包含在datetime 对象的原始创建中?我的另一个选择是剥离 '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

【问题讨论】:

标签: python datetime timezone


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你检查过文档吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 2015-08-18
      • 2012-03-15
      • 2022-01-26
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多