Why Is `%02d` Necessary?


Why is there no difference between print ‘%02d:%02d:%02d’% (now.hour, now.minute, now.second)
and print ‘%d:%d:%d’ % (now.hour, now.minute, now.second)
the “02”'s aren’t necessary even with the date as
print ‘%02d-%02d-%04d’ % (now.month, now.day, now.year)
its better as print ‘%d-%d-%d’ % (now.month, now.day, now.year)

FAQ: Learn Python - Date and Time - Pretty Time

Hi @intergrain,

The 02 just specifies how many characters the number should be. If the current day or month is only a single digit long, using %02d will place an extra 0 at the front. %d doesn’t pad the number at all, using %0Xd will add as many zeroes to the start (left) as you want. You can try this yourself:

>>> print("%d/%d/%d" % (now.month, now.day, now.year))
>>> print("%02d/%02d/%04d" % (now.month, now.day, now.year))
>>> print("%04d/%04d/%04d" % (now.month, now.day, now.year))