Format numbers to strings in Python

Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings:

hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'

or the str.format function starting with 2.7:

"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")

or the string formatting % operator for even older versions of Python, but see the note in the docs:

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

And for your specific case of formatting time, there’s time.strftime:

import time

t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)

Leave a Comment