簡體   English   中英

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

[英]How can I parse a time string containing milliseconds in it with 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

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”

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

上面的 DNS 答案實際上是不正確的。 SO詢問的是毫秒,但答案是微秒。 不幸的是,Python 沒有毫秒指令,只有微秒(參見doc ),但您可以通過在字符串末尾附加三個零並將字符串解析為微秒來解決它,例如:

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

其中time_str被格式化等30/03/09 16:31:32.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 並且由於 .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


我的第一個想法是嘗試將它傳遞給 '30/03/09 16:31:32.123'(在秒和毫秒之間使用句點而不是冒號。)但這不起作用。 快速瀏覽一下文檔表明在任何情況下都會忽略小數秒...

啊,版本差異。 這被報告為一個錯誤,現在在 2.6+ 中您可以使用“%S.%f”來解析它。

來自 python 郵件列表:解析毫秒線程 那里發布了一個似乎可以完成工作的功能,盡管正如作者的評論中提到的那樣,它有點像黑客。 它使用正則表達式來處理引發的異常,然后進行一些計算。

您也可以嘗試在將其傳遞給 strptime 之前預先執行正則表達式和計算。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM