字符串转换为日期时间对象,秒数以浮点数表示

7
>>> a = "2016-03-22 12:33:45.7565"
>>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%f")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .7565
>>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .7565

我曾经使用过%S%f,但如果这是类型float,我怎样处理秒钟呢?
任何帮助将不胜感激。
3个回答

13

小数点后的数字是微秒,并与秒数分开格式化:

>>> a = "2016-03-22 12:33:45.7565"
>>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2016, 3, 22, 12, 33, 45, 756500)

5

这里介绍一种替代方法 - 使用dateutil解析器来完成此任务:

>>> from dateutil.parser import parse
>>> a = "2016-03-22 12:33:45.7565"
>>> parse(a)
datetime.datetime(2016, 3, 22, 12, 33, 45, 756500)

2
In [18]: a = "2016-03-22 12:33:45.7565"

In [19]: datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S.%f")
Out[19]: datetime.datetime(2016, 3, 22, 12, 33, 45, 756500)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接