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

时间:2021-01-18 16:03:03

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

6 个解决方案

#1


235  

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:

Python 2.6增加了一个新的strftime/strptime宏%f,用于处理微秒。不确定是否在任何地方都有记录。但是如果你使用2.6或3.0版本,你可以这样做:

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

Edit: 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:

编辑:我从来没有真正使用过时间模块,所以一开始我没有注意到这个,但是它出现了。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

#2


12  

I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

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

The solution if datetime doesn't support %f and without needing a try/except is:

如果datetime不支持%f,并且不需要尝试/除了:

    (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 

This works for the input string "2010-10-06 09:42:52.266000"

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

#3


3  

To give the code that nstehr's answer refers to (from its source):

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

#4


1  

My first thought was to try passing it '30/03/09 16:31:32.123' (with a period instead of a colon between the seconds and the milliseconds.) But that didn't work. A quick glance at the docs indicates that fractional seconds are ignored in any case...

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

Ah, version differences. This was reported as a bug and now in 2.6+ you can use "%S.%f" to parse it.

啊,版本的差异。这是一个bug,现在在2.6+中可以使用“%S”。% f”来解析它。

#5


1  

from python mailing lists: parsing millisecond thread. There is a function posted there that seems to get the job done, although as mentioned in the author's comments it is kind of a hack. It uses regular expressions to handle the exception that gets raised, and then does some calculations.

从python邮件列表:解析毫秒线程。那里有一个功能似乎完成了工作,尽管正如作者在评论中提到的,这是一种黑客行为。它使用正则表达式来处理引发的异常,然后进行一些计算。

You could also try do the regular expressions and calculations up front, before passing it to strptime.

您还可以尝试在将正则表达式和计算传递到strptime之前先进行这些操作。

#6


0  

For python 2 i did this

对于python 2,我这样做了

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

it prints time "%H:%M:%S" , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my "%H:%M:%S"

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

hope that makes sense :) Example output:

希望这是有意义的)范例输出:

13:31:21.72 Blink 01

13:31:21.72眨眼01


13:31:21.81 END OF BLINK 01

13:31 .81 01眨眼结束


13:31:26.3 Blink 01

13:31:26.3眨眼01


13:31:26.39 END OF BLINK 01

13:31:29 .眨眼01秒。


13:31:34.65 Starting Lane 01

13:31:34.65开始巷01


#1


235  

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:

Python 2.6增加了一个新的strftime/strptime宏%f,用于处理微秒。不确定是否在任何地方都有记录。但是如果你使用2.6或3.0版本,你可以这样做:

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

Edit: 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:

编辑:我从来没有真正使用过时间模块,所以一开始我没有注意到这个,但是它出现了。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

#2


12  

I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

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

The solution if datetime doesn't support %f and without needing a try/except is:

如果datetime不支持%f,并且不需要尝试/除了:

    (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 

This works for the input string "2010-10-06 09:42:52.266000"

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

#3


3  

To give the code that nstehr's answer refers to (from its source):

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

#4


1  

My first thought was to try passing it '30/03/09 16:31:32.123' (with a period instead of a colon between the seconds and the milliseconds.) But that didn't work. A quick glance at the docs indicates that fractional seconds are ignored in any case...

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

Ah, version differences. This was reported as a bug and now in 2.6+ you can use "%S.%f" to parse it.

啊,版本的差异。这是一个bug,现在在2.6+中可以使用“%S”。% f”来解析它。

#5


1  

from python mailing lists: parsing millisecond thread. There is a function posted there that seems to get the job done, although as mentioned in the author's comments it is kind of a hack. It uses regular expressions to handle the exception that gets raised, and then does some calculations.

从python邮件列表:解析毫秒线程。那里有一个功能似乎完成了工作,尽管正如作者在评论中提到的,这是一种黑客行为。它使用正则表达式来处理引发的异常,然后进行一些计算。

You could also try do the regular expressions and calculations up front, before passing it to strptime.

您还可以尝试在将正则表达式和计算传递到strptime之前先进行这些操作。

#6


0  

For python 2 i did this

对于python 2,我这样做了

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

it prints time "%H:%M:%S" , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my "%H:%M:%S"

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

hope that makes sense :) Example output:

希望这是有意义的)范例输出:

13:31:21.72 Blink 01

13:31:21.72眨眼01


13:31:21.81 END OF BLINK 01

13:31 .81 01眨眼结束


13:31:26.3 Blink 01

13:31:26.3眨眼01


13:31:26.39 END OF BLINK 01

13:31:29 .眨眼01秒。


13:31:34.65 Starting Lane 01

13:31:34.65开始巷01