[英]Can't parse microseconds correctly with strptime()
我有一个字符串19:04:01:94891
。
当我将它传递给datetime.datetime.strptime()
作为:
datetime.strptime('19:04:01:94891', "%H:%M:%S:%f")
我得到以下结果:
datetime.datetime(1900, 1, 1, 19, 4, 1, 948910)
但是我希望结果是:
datetime.datetime(1900, 1, 1, 19, 4, 1, 94891)
差异以microseconds
为microseconds
。
当我从文件中读取字符串时,如何在不修改字符串的情况下获得预期结果?
问题是你的输入不是零填充的,所以如果我们在 11 微秒,问题会更糟。 让我们从源头上解决问题,并先清理输入:
def fixMicroseconds(timestamp):
parts = timestamp.split(':')
return ':'.join(
parts[:-1] + ['{:06d}'.format(int(parts[-1]))]
)
现在它将按照 Python 的喜好用零填充为 6 位数字。
这是这个工作的一个例子:
In [1]: def fixMicroseconds(timestamp):
....: parts = timestamp.split(':')
....:
....: return ':'.join(
....: parts[:-1] + ['{:06d}'.format(int(parts[-1]))]
....: )
....:
In [2]: fixMicroseconds('19:04:01:94891')
Out[2]: '19:04:01:094891'
In [3]: fixMicroseconds('19:04:01:13')
Out[3]: '19:04:01:000013'
In [4]: datetime.datetime.strptime(fixMicroseconds('19:04:01:94891'), "%H:%M:%S:%f")
Out[4]: datetime.datetime(1900, 1, 1, 19, 4, 1, 94891)
您确实需要在调用strptime()
之前清理输入,因为这是strptime()
期望的(6 位数)。
从关于strptime()
的文档:
当与
strptime()
方法一起使用时,%f
指令接受一到六位数字和右侧的零strptime()
。
如果您的字符串始终包含一个 5 位微秒数,您可以在解析字符串后截断结果数字:
>>> from datetime import datetime
>>> dt = datetime.strptime('19:04:01:94891', '%H:%M:%S:%f')
>>> dt.replace(microsecond=dt.microsecond//10)
datetime.datetime(1900, 1, 1, 19, 4, 1, 94891)
更可靠的解决方案是将输入字符串左侧的微秒数补零。 由于您已经有了 Python 2 的示例,这里有一个使用 Python 3 的扩展解包的示例:
>>> *rest, ms = '19:04:01:94891'.split(':')
>>> date_string = ':'.join(rest + [ms.zfill(6)])
>>> date_string
'19:04:01:094891'
>>> datetime.strptime(date_string, '%H:%M:%S:%f')
datetime.datetime(1900, 1, 1, 19, 4, 1, 94891)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.