Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string with two digits

I am using the following:

'%.2f%.2f%.2f' % (hours, minutes, seconds)
>>> 0.00:0.00:2.00

How would I force two digits, but no decimal points, so it is:

>>> '00:01:18'
like image 422
David542 Avatar asked Dec 07 '22 00:12

David542


2 Answers

Don't use f when you really want d:

'%02d:%02d:%02d' % (hours, minutes, seconds)

f is for floating point values, d for integers. 02 zero-pads the values:

>>> hours, minutes, seconds = 1, 0, 42
>>> '%02d:%02d:%02d' % (hours, minutes, seconds)
'01:00:42'

You may also want to look into the str.format() method, a newer and more powerful syntax; the equivalent version is:

'{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
like image 106
Martijn Pieters Avatar answered Dec 10 '22 10:12

Martijn Pieters


Why do work you don't have to? Rather than separate values, deal with a single datetime.time:

>>> from datetime import time
>>> h, m, s = 1, 2, 3
>>> t = time(h, m, s)
>>> str(t)
'01:02:03'
like image 34
jonrsharpe Avatar answered Dec 10 '22 11:12

jonrsharpe