来自字符串的datetime对象,float中的秒数

Hac*_*lic 3 python datetime python-2.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
Run Code Online (Sandbox Code Playgroud)

我已经使用%S%f,但我怎么能应付秒钟,如果是类型float

任何帮助,将不胜感激

sna*_*erb 8

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

>>> 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)
Run Code Online (Sandbox Code Playgroud)


ale*_*cxe 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)
Run Code Online (Sandbox Code Playgroud)