我可以使用 time.strptime
解析包含日期/时间的字符串>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)
如何解析包含毫秒的时间字符串?
>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
data_string[found.end():])
ValueError: unconverted data remains: .123
最佳答案
Python 2.6 添加了新的 strftime/strptime 宏 %f
。文档有点误导,因为它们只提到微秒,但 %f
实际上解析 any 秒的小数部分,最多 6 位,这意味着它也适用于毫秒甚至厘秒或分秒。
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
但是,time.struct_time实际上并不存储毫秒/微秒。你最好使用 datetime
,像这样:
>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000
如您所见,.123
被正确解释为 123 000
微秒。
https://stackoverflow.com/questions/698223/