如何将包含 7 位毫秒数的日期字符串转换为 Python 中的日期

Dgs*_*tah 6 python datetime date

当毫秒有 6 位数字时,%f 有效,但如果超过 6 位数字,则会引发错误。我有一个临时解决方案,将第 7 位硬编码为 0,但是有更好的方法吗?目前以下作品

print (datetime.datetime.strptime(('2014-11-19 00:00:00.0000000').strip(), '%Y-%m-%d  %H:%M:%S.0%f')).date()
Run Code Online (Sandbox Code Playgroud)

use*_*028 7

根据datetime.strptime() https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior的文档,技术说明 (4),%f 仅接受 1 - 6 个字符:

%f 是 C 标准中格式字符集的扩展(但在日期时间对象中单独实现,因此始终可用)。当与 strptime() 方法一起使用时,%f 指令接受一到六位数字以及右侧的零填充。

我不相信你已经正确解决了问题。您不应该在字符串中添加零前缀,而应将所有超过 6 的内容删除(这对时间的贡献不太重要)。

像这样的东西:

s='2014-11-19 00:00:00.0000000'
print (datetime.datetime.strptime((s[:26]).strip(), '%Y-%m-%d  %H:%M:%S.%f')).date()
Run Code Online (Sandbox Code Playgroud)