python - 无法使用 strptime() 正确解析微秒

标签 python python-2.7 datetime

我有一个字符串 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)

区别在于微秒

当我从文件中读取字符串时,如何在不修改字符串的情况下获得预期的结果?

最佳答案

问题是您的输入没有用零填充,所以如果我们在 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 位数字)。

关于python - 无法使用 strptime() 正确解析微秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38301650/

相关文章:

javascript - 从字符串解析为日期时间

javascript - Powerbuilder/Javascript HTML Datawindow SetItem 日期时间失败

java - 无法在 Java8 中将悉尼转换为布里斯类 LocalDateTime

python - 在 Jinja2 模板中使用 utf-8 字符

python - 错误没有名为 curses 的模块

python - 从嵌套 JSON 文件中提取值

python-2.7 - 如何在arch linux中用python 2完全替换python 3

python - 在python中复制文件

python - Pandas :读取列中包含特殊字符的文件

python - 如何将额外的参数传递给 Python 装饰器?