datetime objects format
You can convert them to strings and simply pad them:
import datetime
d = datetime.datetime(2012, 5, 25)
m = str(d.month).rjust(2, '0')
print(m) # Outputs "05"
Or you could just a str.format
:
import datetime
d = datetime.datetime(2012, 5, 25)
print("{:0>2}".format(d.month))
EDIT: To answer the updated question, have you tried this?
import datetime
d = datetime.datetime(2012, 5, 25)
print("{:0>4}-{:0>2}-{:0>2}".format(d.year, d.month, d.day))
You said you were originally printing them using string formatting, so what did you change? This code:
print "%s-%s-%s"%(date.year, date.month, date.day, etc., len(str) )
Doesn't really make any sense, since I'm a little unclear as to what arguments you are passing in. I assume just date.year
, date.month
, and date.day
, but it's unclear. What action are you performing with len(str)
?
zfill is easier to remember:
In [19]: str(dt.month).zfill(2)
Out[19]: '07'
You can print the individual attributes using string formatting:
print ('%02d' % (mydate.month))
Or more recent string formatting (introduced in python 2.6):
print ('{0:02d}'.format(a.month)) # python 2.7+ -- '{:02d}' will work
Note that even:
print ('{0:%m}'.format(a)) # python 2.7+ -- '{:%m}' will work.
will work.
or alternatively using the strftime method of datetime objects:
print (mydate.strftime('%m'))
And just for the sake of completeness:
print (mydate.strftime('%Y-%m-%d'))
will nicely replace the code in your edit.