我如何用python解析一个包含毫秒的时间字符串?

我能够用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
255293 次浏览

我的第一个想法是尝试传递“30/03/09 16:31:32.123”(在秒和毫秒之间用句号而不是冒号)。但这并没有起作用。快速浏览一下文档就会发现,在任何情况下,小数秒都被忽略了……

啊,版本差异。这是报告为错误,现在在2.6+中,您可以使用“%S。%f"来解析它。

from python邮件列表:解析毫秒线程。有一个函数张贴在那里,似乎可以完成这项工作,尽管正如作者的评论中提到的,这是一种hack。它使用正则表达式来处理引发的异常,然后进行一些计算。

您还可以在将正则表达式传递给strptime之前,尝试预先执行正则表达式和计算。

给出nstehr的回答所引用的代码(来自其来源):

def timeparse(t, format):
"""Parse a time string that might contain fractions of a second.


Fractional seconds are supported using a fragile, miserable hack.
Given a time string like '02:03:04.234234' and a format string of
'%H:%M:%S', time.strptime() will raise a ValueError with this
message: 'unconverted data remains: .234234'.  If %S is in the
format string and the ValueError matches as above, a datetime
object will be created from the part that matches and the
microseconds in the time string.
"""
try:
return datetime.datetime(*time.strptime(t, format)[0:6]).time()
except ValueError, msg:
if "%S" in format:
msg = str(msg)
mat = re.match(r"unconverted data remains:"
" \.([0-9]{1,6})$", msg)
if mat is not None:
# fractional seconds are present - this is the style
# used by datetime's isoformat() method
frac = "." + mat.group(1)
t = t[:-len(frac)]
t = datetime.datetime(*time.strptime(t, format)[0:6])
microsecond = int(float(frac)*1e6)
return t.replace(microsecond=microsecond)
else:
mat = re.match(r"unconverted data remains:"
" \,([0-9]{3,3})$", msg)
if mat is not None:
# fractional seconds are present - this is the style
# used by the logging module
frac = "." + mat.group(1)
t = t[:-len(frac)]
t = datetime.datetime(*time.strptime(t, format)[0:6])
microsecond = int(float(frac)*1e6)
return t.replace(microsecond=microsecond)


raise

Python 2.6添加了一个新的strftime/strptime宏%f。文档有一点误导,因为他们只提到微秒,但%f实际上用 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微秒。

我知道这是一个老问题,但我仍然在使用Python 2.4.3,我需要找到一种更好的方法将数据字符串转换为日期时间。

如果datetime不支持%f并且不需要try/except,解决方案是:

    (dt, mSecs) = row[5].strip().split(".")
dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
mSeconds = datetime.timedelta(microseconds = int(mSecs))
fullDateTime = dt + mSeconds

这适用于输入字符串“2010-10-06 09:42:52.266000”

对于python 2,我这样做

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

它输出时间“%H:%M:%S”,将time.time()分割为两个子字符串(在。之前和之后)xxxxxxx。由于.xx是我的毫秒,我将第二个子字符串添加到我的“%H:%M:%S”

希望这有意义:) 示例输出:< / p >

< p > 13:31:21.72 眨眼01 < / p >
< p > 13:31:21.81


< p > 13:31:26.3 眨眼01 < / p >
< p > 13:31:26.39


< p > 13:31:34.65 起跑道01


以上DNS应答实际上是不正确的。SO问的是毫秒,但答案是微秒。不幸的是,Python没有毫秒指令,只有微秒指令(参见医生),但你可以通过在字符串末尾追加三个零并将字符串解析为微秒来解决这个问题,例如:

datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')

其中time_str的格式类似于30/03/09 16:31:32.123

希望这能有所帮助。