Python strftime - date without leading 0? Python strftime - date without leading 0? python python

Python strftime - date without leading 0?

Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero.

For example %Y/%-m/%-d.

This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %Y/%#m/%#d.

We can do this sort of thing with the advent of the format method since python2.6:

>>> import datetime>>> '{dt.year}/{dt.month}/{}'.format(dt ='2013/4/19'

Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:

>>> '{dt:%A} {dt:%B} {}, {dt.year}'.format('Wednesday December 3, 2014'

And as of python3.6, this can be expressed as an inline formatted string:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> import datetime>>> dt =>>> f'{dt:%A} {dt:%B} {}, {dt.year}''Monday August 29, 2016'

Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y(2009, 5, 7, 17, 17, 17, 3, 127, 1)>>> time.strftime('%Y %m %d', y)'2009 05 07'>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')'2009 5 7'