마이크로 초를 얻기 위해 파이썬에서 strftime ()과 함께 % f 사용하기
나는 strftime ()을 마이크로 초 정밀도로 사용하려고하는데, 이것은 % f ( 여기에 언급 된대로 )를 사용하여 가능해 보인다 . 그러나 다음 코드를 시도 할 때 :
import time
import strftime from time
print strftime("%H:%M:%S.%f")
... 시간, 분 및 초를 얻지 만 % f는 마이크로 초 기호없이 % f로 인쇄합니다. Ubuntu에서 Python 2.6.5를 실행하고 있으므로 괜찮을 것이고 % f가 지원되어야합니다 (내가 아는 한 2.6 이상에서 지원됨).
이를 얻기 위해 datetime의 strftime 함수를 사용할 수 있습니다. 문제는 시간의 strftime이 마이크로 초 정보를 전달하지 않는 타임 튜플을 받아 들인다는 것입니다.
from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")
트릭을해야합니다!
잘못된 문서를보고 있습니다. time
모듈은 다른 문서가 있습니다 .
다음 과 같이 datetime
모듈을 사용할 수 있습니다 strftime
.
>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now.strftime("%H:%M:%S.%f")
'12:19:40.948000'
이것은 일을해야한다
import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")
인쇄됩니다
HH:MM:SS.microseconds
예를 들면 14:38:19.425961
기능을 time
사용 하여 모듈 에서 마이크로 초 정밀도를 얻을 수도 time()
있습니다.
( time.time()
epoch 이후의 시간을 초 단위로 반환합니다. 소수 부분은 원하는 시간 인 마이크로 초 단위입니다.)
>>> from time import time
>>> time()
... 1310554308.287459 # the fractional part is what you want.
# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)
Python의 time
모듈을 사용하면 %f
.
여전히 time
모듈 만 사용 하려는 사용자를 위한 해결 방법은 다음과 같습니다.
now = time.time()
mlsec = repr(now).split('.')[1][:3]
print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))
2017-01-16 16 : 42 : 34.625 EET 와 같은 결과를 얻을 수 있습니다 (예, 밀리 초를 사용합니다).
코드를 세부 사항으로 나누려면 아래 코드를 Python 콘솔에 붙여 넣으세요.
import time
# Get current timestamp
now = time.time()
# Debug now
now
print now
type(now)
# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)
# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec
# Get your required timestamp string
timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
print timestamp
설명을 위해 Python 2.7.12 결과도 여기에 붙여 넣습니다.
>>> import time
>>> # get current timestamp
... now = time.time()
>>> # debug now
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
>>> type(struct_now)
<type 'time.struct_time'>
>>> # print nicely formatted date
... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
2017-01-16 16:51:33 EET
>>> # get miliseconds
... mlsec = repr(now).split('.')[1][:3]
>>> print mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>
When the "%f" for micro seconds isn't working, please use the following method:
import datetime
def getTimeStamp():
dt = datetime.datetime.now()
return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)
If you want speed, try this:
def _timestamp(prec=0):
t = time.time()
s = time.strftime("%H:%M:%S", time.localtime(t))
if prec > 0:
s += ("%.9f" % (t % 1,))[1:2+prec]
return s
Where prec
is precision -- how many decimal places you want. Please note that the function does not have issues with leading zeros in fractional part like some other solutions presented here.
If you want an integer, try this code:
import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])
Output:
1545474382803
참고URL : https://stackoverflow.com/questions/6677332/using-f-with-strftime-in-python-to-get-microseconds
'IT story' 카테고리의 다른 글
반품 된 품목 수를 제한하려면 어떻게합니까? (0) | 2020.08.17 |
---|---|
명령 줄 Zsh의 주석 (0) | 2020.08.17 |
OpenMP에서 원자와 중요의 차이점은 무엇입니까? (0) | 2020.08.17 |
커밋 ID가 주어지면 현재 분기에 커밋이 포함되어 있는지 확인하는 방법은 무엇입니까? (0) | 2020.08.17 |
조건이 목록의 요소에 대해 유지되는지 확인하는 Pythonic 방법 (0) | 2020.08.17 |