Format seconds as float

I want to output:

"14:48:06.743174"

      

This is the closest I can get:

`"14:48:06"` 

      

from:

t = time.time()
time.strftime("%H:%M:%S",time.gmtime(t))

      

+3


source to share


1 answer


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'

      

+8


source







All Articles