【问题标题】:How can I parse a custom string as a timezone aware datetime?如何将自定义字符串解析为时区感知日期时间?
【发布时间】:2022-01-18 20:18:05
【问题描述】:

如何解析

18 January 2022, 14:50 GMT-5

作为时区感知日期时间。

pytz.timezone('GMT-5')

失败。 看来我可能需要解析 GMT 部分,并在解析后手动应用 5 小时偏移量?

【问题讨论】:

  • 你的所有日期都是“GMT-5”吗?
  • 不,它会有所不同,但它似乎是 GMT 或 UTC

标签: python-3.x pytz


【解决方案1】:

嗯,也许吧:

import re
import datetime
foo = "18 January 2022, 14:50 GMT-5"
bar = re.sub(r"[+-]\d+$", lambda m: "{:05d}".format(100 * int(m.group())), foo)
print(datetime.datetime.strptime(bar, "%d %B %Y, %H:%M %Z%z" ))

我认为这给了你:

2022-01-18 14:50:00-05:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    相关资源
    最近更新 更多