本文介绍了如何使用python解析包含毫秒的时间字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 time.strptime 解析包含日期/时间的字符串

I am able to parse strings containing date/time with 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)

如何解析包含毫秒的时间字符串?

How can I parse a time string that contains milliseconds?

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

Python 2.6 added a new strftime/strptime macro %f, which does microseconds. Not sure if this is documented anywhere. But if you're using 2.6 or 3.0, you can do this:

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

编辑:我从来没有真正使用时间模块,所以我没有注意到这一点,但似乎time.struct_time不' t实际存储毫秒/微秒。您可以使用 datetime 更好,如下所示:

I never really work with the time module, so I didn't notice this at first, but it appears that time.struct_time doesn't actually store milliseconds/microseconds. You may be better off using datetime, like this:

>>> 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解析包含毫秒的时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:19