Reputation: 57
I have seen many questions about formatting floats
and limiting decimal places, but I have not seen both done at once. I want the values for my variable seconds
to always be represented as SS.mmm.
I have
t = int(input('time?: '))
seconds = (t / 1000) % 60
minutes = (t // (1000 * 60)) % 60
hours = (t // (1000 * 60 * 60)) % 24
I want to print hours
, minutes
, and seconds
so that it will always follow HH:MM:SS.mmm
My attempt:
print('{}:{}:{}'.format("%02d" % hours, "%02d" % minutes, ("%.3f" % seconds).zfill(2)))
I end up getting HH:MM:S.mmm sometimes. I need there to be two seconds digits even if there is a leading zero.
Upvotes: 1
Views: 2276
Reputation: 582
You should be able to do the following with .format()
:
print('{:0>2d}:{:0>2d}:{:06.3f}'.format(hours,minutes,seconds))
In particular, 0>2d
forces the integers hours
and minutes
to be of length 2. Further, 06.3f
implies that the entire float representation should be 6 characters long (including the '.'
) and have 3 decimal places to the right of the period.
Upvotes: 3