【问题标题】:Using datetime.strptime with microseconds (ValueError: unconverted data remains: :00)使用带有微秒的 datetime.strptime(ValueError:未转换的数据仍然存在:00)
【发布时间】:2021-12-28 16:48:16
【问题描述】:

我正在尝试使用以下代码将此日期“2021-09-29 00:05:00+00:00”转换为“str”:

date1 = '2021-09-29 00:05:00+00:00'

date1 = datetime.datetime.strptime(date1,'%Y-%m-%d %H:%M:%S+%f')

但我得到了错误:

“ValueError:未转换的数据仍然存在:00”。

我不知道如何处理微秒。对于使用具有该日期格式的 strptime 的任何帮助将不胜感激!

提前致谢。

【问题讨论】:

  • 这不是微秒,而是以小时和分钟为单位的时区偏移量。
  • 00:00 究竟是什么意思?这绝对不应该是毫秒,但我认为这也不是时区偏移量。
  • @MarkTolonen 我问 OP 他们是否知道它是什么。我理解你的假设,但我不确定它是否正确。
  • 这能回答你的问题吗? How do I parse an ISO 8601-formatted date?
  • 使用%z 而不是+%f

标签: python datetime


【解决方案1】:

+00:00 偏移量是以小时和分钟为单位的时区偏移量。根据strftime() and strptime() Format Codes 文档,使用%z 进行解析:

Directive Meaning Example Notes
%z UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive) (empty), +0000, -0400, +1030, +063415, -030712.345216 (6)

根据注释 6 中的详细信息,直到 Python 3.7 才支持冒号 (:) 的语法:

在 3.7 版中更改:%z 指令提供给 strptime() 方法时,UTC 偏移量可以使用冒号作为小时、分钟和秒之间的分隔符。例如,'+01:00:00' 将被解析为一小时的偏移量。此外,提供'Z''+00:00' 相同。

from datetime import datetime

s = '2021-09-29 00:05:00+00:00'
t = datetime.strptime(s,'%Y-%m-%d %H:%M:%S%z')
print(t)

输出:

2021-09-29 00:05:00+00:00

【讨论】:

    猜你喜欢
    • 2020-04-25
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多