Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format seconds as float

Tags:

python

I wish to output:

"14:48:06.743174"

This is the closest I can get:

`"14:48:06"` 

with:

t = time.time()
time.strftime("%H:%M:%S",time.gmtime(t))
like image 298
Baz Avatar asked May 07 '15 12:05

Baz


People also ask

How to convert seconds into hh mm ss format in Python?

Use the timedelta() constructor and pass the seconds value to it using the seconds argument. The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds ( days, hh:mm:ss.ms ) format. For example, datetime.

How to convert time format to seconds in Python?

Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch. Use the timestamp() method. If your Python version is greater than 3.3 then another way is to use the timestamp() method of a datetime class to convert datetime to seconds.

How to print time in hh mm ss format in Python?

strftime('%H:%M:%S', time.


1 Answers

According to the manual on time there is no straight forward way to print microseconds (or seconds as 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 a decimal number [0,999999], zero-padded on the left

>>> import datetime
>>> datetime.datetime.now().strftime('%H:%M:%S.%f')
'14:07:11.286000'

Or when you have your 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 to have more control over how microseconds get formatted (for example displaying only 3 places instead of 6) you will either have to crop the text (using [:-3]):

>>> datetime.datetime.utcfromtimestamp(t).strftime('%H:%M:%S.%f')[:-3]
'12:08:32.463'

Or format it by hand:

>>> '.{:03}'.format(int(dt.microsecond/1000))
'.463'
like image 146
Vyktor Avatar answered Oct 31 '22 12:10

Vyktor