datetime.strptime() not padding 0's

John Gordon gordon at panix.com
Tue Apr 23 17:38:18 EDT 2013


In <mailman.995.1366751728.3114.python-list at python.org> Rodrick Brown <rodrick.brown at gmail.com> writes:

> I thought I read some where that strptime() will pad 0's for day's for some
> reason this isnt working for me and I'm wondering if i'm doing something
> wrong.

> >>> from datetime import datetime
> >>> dt = datetime.strptime('Apr 9 2013', '%b %d %Y')
> >>> dt.day
> 9

> How can I get strptime to run 09? instead of 9

dt.day is just an integer.  If you want to print it with zero padding,
use a format string:

>>> n = 9
>>> print n
9
>>> print '%02d' % n
09

or for python 3:
>>> print("{0:02d}".format(n))
09

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list