无法使用strptime()正确解析微秒 [英] Can't parse microseconds correctly with strptime()
问题描述
我有一个字符串 19:04:01:94891
。
当我将其传递给 datetime.datetime.strptime()
as:
When I pass this to datetime.datetime.strptime()
as:
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)
差异在于微秒
。
如何在不进行修改的情况下获得预期结果
How can I get the expected result without modifying the string as I am reading the string from a file?
推荐答案
问题是您输入的内容不是零填充的,因此,如果我们以11微秒为单位,问题将更加严重。让我们从源头上解决问题,然后首先清理输入:
The problem is that your input isn't zero-padded, so the problem would be even worse if we were at, say, 11 microseconds. Let's fix the problem at it's source, and clean up the input first:
def fixMicroseconds(timestamp):
parts = timestamp.split(':')
return ':'.join(
parts[:-1] + ['{:06d}'.format(int(parts[-1]))]
)
现在它将被零填充为6位数字Python更喜欢。
Now it will be zero-padded to 6 digits as Python prefers.
以下是此工作的示例:
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()$ c之前,您确实需要清理输入内容$ c>,因为这就是
strptime()
的期望值(6位数字)。
You really need to clean up the input before the call to strptime()
, because that's what strptime()
expects (6 digits).
这篇关于无法使用strptime()正确解析微秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!