Yarin Yarin - 1 year ago 192
Python Question

Python datetime formatting without zero-padding

Is there a format for printing Python datetimes that won't use zero-padding on dates and times?

Format I'm using now:

mydatetime.strftime('%m/%d/%Y %I:%M%p')

Result: 02/29/2012 05:03PM

Desired: 2/29/2012 5:03PM

What format would represent the month as '2' instead of '02', and time as '5:03PM' instead of '05:03PM'

Answer Source

The formatting options available with datetime.strftime() will all zero-pad. You could of course roll you own formatting function, but the easiest solution in this case might be to post-process the result of datetime.strftime():

s = mydatetime.strftime('%m/%d/%Y %I:%M%p').lstrip("0").replace(" 0", " ")

(That is, if you decide that doing so is really worth the trouble. Why not simply leave the zeros in?)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download