我可以使用 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
%f
。 - phunehehe%f
中的数字会在右侧添加零(而不是左侧),直到小数点后有六位数字。数字 1 被解析为 100000,数字 12 被解析为 120000,而数字 1234567 则产生ValueError: unconverted data remains: 7
的错误信息。 - user443854%f
可以用于类似 '23.123' 的字符串。(很抱歉我没有解释一下 123,000µs = 123ms;有时候我会忘记还有一些国家没有采用国际单位制,因此对标准指数前缀不太熟悉。) - Michael Scheper