我怎样才能parsing包含毫秒的时间string在Python中?

我能够用time.strptimeparsing包含date/时间的string

>>> 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) 

如何parsing包含毫秒的时间string?

 >>> 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 / strptimemacros%f ,这个微秒。 不知道这是否logging在任何地方。 但是,如果你使用2.6或3.0,你可以这样做:

 time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f') 

编辑:我从来没有真正的time模块工作,所以我一开始没有注意到这一点,但似乎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 

我知道这是一个老问题,但我仍然使用Python 2.4.3,我需要find一个更好的方式将数据string转换为date时间。

解决scheme如果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 

这适用于inputstring“2010-10-06 09:42:52.266000”

给出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 

我的第一个想法是尝试通过它'30 / 03/09 16:31:32.123'(有一段时间,而不是在秒和毫秒之间的冒号),但没有奏效。 快速浏览一下文档,可以发现在任何情况下都会忽略小数秒。

啊,版本差异。 这被报告为一个错误 ,现在在2.6以上,你可以使用“%S.%f”来parsing它。

从python邮件列表: parsing毫秒线程 。 虽然在作者的评论中提到这是一种黑客攻击,但在那里有一个function似乎完成了工作。 它使用正则expression式来处理引发的exception,然后进行一些计算。

你也可以尝试前面的正则expression式和计算,然后传递给strptime。

对于Python 2我做到了这一点

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

它打印时间“%H:%M:%S”,将time.time()分成两个子string(之前和之后)。xxxxxxx.xx和.xx是我的毫秒我添加第二个子string到我的“ H:%M:%S”

希望有道理:)示例输出:

13:31:21.72闪烁01


13:31:21.81结束01


13:31:26.3闪烁01


13:31:26.39结束01


13:31:34.65从车道01开始