Format seconds as float
According to the manual,time
there is no direct way to print microseconds (or seconds as a float):
>>> time.strftime("%H:%M:%S.%f",time.gmtime(t))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid format string
However, datetime.datetime
format provides %f
, which is defined as:
Microsecond as decimal [0.999999], with a zero tab on the left
>>> import datetime
>>> datetime.datetime.now().strftime('%H:%M:%S.%f')
'14:07:11.286000'
Or, when you have a value stored in t = time.time()
, you can use datetime.datetime.utcfromtimestam()
:
>>> datetime.datetime.utcfromtimestamp(t).strftime('%H:%M:%S.%f')
'12:08:32.463000'
I'm afraid that if you want more control over how microseconds are formatted (for example, displaying only 3 spaces instead of 6), you either have to truncate the text (using [:-3]
):
>>> datetime.datetime.utcfromtimestamp(t).strftime('%H:%M:%S.%f')[:-3]
'12:08:32.463'
Or format it manually:
>>> '.{:03}'.format(int(dt.microsecond/1000))
'.463'
source to share