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'
Good answer from Chris Freeman on Linux.
On windows, it's:
Thought that might help.
The other alternate to avoid the "all or none" leading zero aspect above is to place a minus in front of the field type:
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.
The new string formatting system provides an alternative to
strftime
. It's quite readable -- indeed, it might be preferable tostrftime
on that account. Not to mention the fact that it doesn't zero-pad:Since you probably want zero padding in the minute field, you could do this:
If you want "regular" time instead of "military" time, you can still use the standard
strftime
specifiers as well. Conveniently, for our purposes,strftime
does provide a code for the 12-hour time padded with a blank instead of a leading zero:This becomes somewhat less readable, alas. And as @mlissner points out,
strftime
will fail on some (all?) platforms for dates before 1900.Accepted answer not a proper solution (IMHO) The proper documented methods:
In Linux "#" is replaced by "-":
%-d, %-H, %-I, %-j, %-m, %-M, %-S, %-U, %-w, %-W, %-y, %-Y
In Windows "-" is replaced by "#":
%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y
Source: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx
As stated by Sagneta: The # hash trick on Windows is only available to native python executable. this will not work for cygwin-based python implementations.
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 ofdatetime.strftime()
:(That is, if you decide that doing so is really worth the trouble. Why not simply leave the zeros in?)