【问题标题】:Python strptime with "+00" timezone offset format?具有“+00”时区偏移格式的Python strptime?
【发布时间】:2019-09-02 12:02:41
【问题描述】:

如何解析格式为 +00 的时区偏移量? Python 3 或 Python 2

from datetime import datetime
s = '2019-04-10 21:49:41.607472+00'
# What must I replace <XX> with, to parse +00 as the timezone offset
d = datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f<XX>')

【问题讨论】:

    标签: python date time timezone


    【解决方案1】:

    您可以为此使用dateutil's parse

    from dateutil.parser import parse
    s = '2019-04-10 21:49:41.607472+00'
    parse(s)
    

    datetime.datetime(2019, 4, 10, 21, 49, 41, 607472, tzinfo=tzutc())

    【讨论】:

      【解决方案2】:

      strptime 使用%z±HHMM[SS[.ffffff]] 的格式指定UTC 偏移量。由于需要几分钟并且您的示例输入只有几小时,因此您可以在解析之前将 '00' 连接到字符串:

      datetime.strptime(s + '00', '%Y-%m-%d %H:%M:%S.%f%z')
      

      【讨论】:

      • Python 2.7 说*** ValueError: 'z' is a bad directive in format
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多