我能够用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

当前回答

对于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”

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

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起跑道


其他回答

我知道这是一个老问题,但我仍然在使用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.6添加了新的strftime/strptime宏%f。文档中只提到了微秒,这有点误导人,但%f实际上解析秒的任何小数部分,最多有6位,这意味着它也适用于毫秒,甚至厘秒或分秒。

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

然而,时间。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被正确地解释为123000微秒。

对于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”

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

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起跑道


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

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