파이썬으로 밀리 초를 포함하는 시간 문자열을 어떻게 구문 분석 할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/698223

문제

날짜/시간을 포함하는 문자열을 구문 분석 할 수 있습니다. 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은 새로운 스트프 프리 타임/strptime 매크로를 추가했습니다 %f, 마이크로 초. 이것이 어디서나 문서화되어 있는지 확실하지 않습니다. 그러나 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을 사용하고 있으며 데이터 문자열을 DateTime으로 변환하는 더 나은 방법을 찾아야했습니다.

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 

이것은 입력 문자열 "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

나의 첫 번째 생각은 그것을 통과시키는 것이 었습니다. 문서를 빠르게 한 눈에 보면 어떤 경우에도 분수 초가 무시된다는 것을 나타냅니다.

아, 버전 차이. 이했다 버그로보고되었습니다 그리고 이제 2.6+에서는 "%S.%f"를 사용하여 구문 분석 할 수 있습니다.

파이썬 메일 링리스트에서 : 밀리 초 스레드를 구문 분석합니다. 저자의 의견에 언급 된 바와 같이, 그것은 일종의 해킹입니다. 정규 표현식을 사용하여 제기되는 예외를 처리 한 다음 계산을 수행합니다.

또한 정규 표현식과 계산을 앞쪽으로 전달하기 전에 시도 할 수도 있습니다.

Python 2의 경우 나는 이것을했다

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

시간 "%h :%m :%s"를 인쇄하고 시간을 두 개의 하위 문자로 나눕니다 (전후에) xxxxxxxx.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


위의 DNS 답변 실제로 잘못되었습니다. SO는 밀리 초에 대해 묻는 것이지만 대답은 마이크로 초에 대한 것입니다. 불행히도, Python 's는 밀리 초에 대한 지침이 없으며 마이크로 초만 문서), 그러나 당신은 문자열 끝에 3 개의 0을 추가하고 문자열을 마이크로 초로 구문 분석하여 다음과 같은 것들을 해결할 수 있습니다.

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

어디 time_str 같은 형식입니다 30/03/09 16:31:32.123.

도움이 되었기를 바랍니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top