Python datetime formatting without zero-padding

Yarin picture Yarin · Mar 2, 2012 · Viewed 86k times · Source

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

ChrisFreeman picture ChrisFreeman · May 1, 2015

The other alternate to avoid the "all or none" leading zero aspect above is to place a minus in front of the field type:

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

Then this: '4/10/2015 03:00AM'

Becomes: '4/10/2015 3:00AM'

You can optionally place a minus in front of the day if desired.

Edit: The minus feature derives from the GNU C library (“glibc”) as mentioned in the Linux strftime manpage under “Glibc notes”