【问题标题】:Timestamp string to datetime (python)时间戳字符串到日期时间(python)
【发布时间】:2022-01-03 01:36:56
【问题描述】:

我有这个时间戳字符串:

x = 2021-11-24T16:05:51.399+0000

我正在努力让解析在小数点后通过。到目前为止,这是我的尝试:

datetime.datetime.strptime(x,"%Y-%m-%dT%H:%M:%S.%f+")

运行此行的当前错误:

ValueError: unconverted data remains: 0000

【问题讨论】:

  • 有点老套但高效:datetime.fromisoformat(x[:-2] + ':' + x[-2:]) - fromisoformat 需要 UTC 偏移量为 hh:mm 的形式,即中间有冒号。

标签: python timestamp python-datetime


【解决方案1】:

在格式末尾添加%z以匹配UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

>>> 从日期时间导入日期时间 >>> >>> x = '2021-11-24T16:05:51.399+0000' >>> datetime.strptime(x,"%Y-%m-%dT%H:%M:%S.%f%z") datetime.datetime(2021, 11, 24, 16, 5, 51, 399000, tzinfo=datetime.timezone.utc)

【讨论】:

    猜你喜欢
    • 2012-10-25
    • 2013-07-29
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多