>>> 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
,我该如何处理秒数?
任何帮助将不胜感激
答案 0 :(得分:7)
小数点后面的数字是微秒,并且与秒数分开格式化:
>>> 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)
答案 1 :(得分: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)
答案 2 :(得分:1)
只是另一种方法 - 让dateutil
parser完成工作:
>>> from dateutil.parser import parse
>>> a = "2016-03-22 12:33:45.7565"
>>> parse(a)
datetime.datetime(2016, 3, 22, 12, 33, 45, 756500)