% formatting operator already supports 0-padding, just specify the width as
02. Also, you can pass a tuple to combine multiple numbers into the same string with a single format:
"%02d:%02d:%02d" % (h, m, s).
In Python 3 the
format string method is slightly preferred to the
% operator, with Python 3.6 further allowing the format string to reference the variables directly. Using such formatted string literals or f-strings, the formatting would be expressed as:
As pointed out in the comments, if you're starting with
datetime objects to begin with, you can use their own formatting functionality instead.