python으로 밀리초가 포함된 시간 문자열을 구문 분석하려면 어떻게 해야 하는가?
날짜/시간이 포함된 문자열을 시간.스트립타임으로 구문 분석할 수 있다.
>>> 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에 새로운 스트립타임/스트립타임 매크로 추가%f
문서들은 단지 마이크로초만 언급하기 때문에 약간 오해의 소지가 있다.%f
실제로 최대 6자리 숫자로 10진수 분율을 구문 분석하는데, 이는 밀리초 또는 센티초 또는 데시초에도 작동한다는 것을 의미한다.
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을 사용하고 있고 나는 데이터 문자열을 데이터타임으로 변환하는 더 나은 방법을 찾아야 했다.
시도/예외 없이 %f를 지원하지 않는 datetime의 솔루션은 다음과 같다.
(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는 밀리초 정도 묻고 있지만 답은 마이크로초다.불행히도 파이썬은 1밀리초 동안 지시사항이 없지만(문서 참조) 문자열 끝에 0 3개를 추가하고 문자열을 마이크로초 단위로 구문 분석하면 해결할 수 있다.
datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')
어디에time_str
형식은 다음과 같다.30/03/09 16:31:32.123
.
이게 도움이 되길 바래.
나의 첫 번째 생각은 '30/03/09 16:31:32.123'(초와 밀리초 사이에 콜론 대신 기간을 두고)을 통과해 보는 것이었다.그러나 그것은 효과가 없었다.문서를 잠깐 보면 어떤 경우에도 분절초는 무시된다는 것을 알 수 있다...
아, 버전 차이점.이것은 버그로 보고되었으며, 이제 2.6 이상에서는 "%S.%f"를 사용하여 구문 분석할 수 있다.
python 메일링 리스트에서: 밀리초 스레드 구문 분석.저자의 논평에서 언급된 것처럼 그것은 일종의 해킹이다.정규식을 사용하여 제기되는 예외를 처리한 다음, 몇 가지 계산을 한다.
여러분은 또한 정규 표현과 계산을 먼저 한 후에 그것을 스트립타임으로 넘길 수도 있다.
python 2를 위해서 나는 이렇게 했다.
print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])
시간 "%H:%M:%S"를 출력하여 time.time()을 두 개의 서브스트링(. 전후) xxxxxxxx로 분할한다.xx 및 .xx가 msec이므로 "%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
'programing' 카테고리의 다른 글
후크를 사용하여 지도(사전) 상태 변경 시 구성 요소가 업데이트되지 않음 (0) | 2022.03.19 |
---|---|
사용자 지정 후크가 useEffect에서 제대로 작동하지 않음 (0) | 2022.03.19 |
Vue 2방향 프로펠러 바인딩 (0) | 2022.03.19 |
Vuetify에서 사용자 지정 SVG 아이콘을 추가하는 방법 - Vue (0) | 2022.03.17 |
관찰 가능한 캐스팅 결과.각 2에서 각 유형별로 포크조인 (0) | 2022.03.17 |