Removing leading zeroes in Python's strftime
Update: See the comment below from aloschilov for the best way to removing leading zeroes, which is to use a - before the formatter (after the %), e.g.: %-H. I was unaware of this syntax when I wrote this tip.
Python's strftime does not have options for single digit days or hours, which means you can end up with very clinical looking formats like:
02:24 PM - 09 Jan 2014
A simple way to fix this is to combine the power of strftime and regular string formatting. Along with a little mod trickery, you can get more human friendly looking formats this way:
d.strftime('%d:%%M %%p - %d %%b %%Y' % (
d.hour % 12 if d.hour % 12 else 12, d.day))
which returns, e.g.:
2:24 PM - 9 Jan 2014
Written by Scott Bradley
Related protips
2 Responses
I believe that you are wrong and there is a simpler way to implement human friendly formats. You need to insert hyphen within value placeholder:
>>> dt_object.strftime("%H:%M")
'01:05'
>>> dt_object.strftime("%-H:%M")
'1:05'
Thanks @aloschilov. Your comment is the true pro tip here. Thank you for the correction!