Last Updated: February 25, 2016
· scott2b

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,

which returns, e.g.:

2:24 PM - 9 Jan 2014

2 Responses
Add your response

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")
>>> dt_object.strftime("%-H:%M")
over 1 year ago ·

Thanks @aloschilov. Your comment is the true pro tip here. Thank you for the correction!

over 1 year ago ·