Python datetime retrieves double-digit month and day values

Is there a way to extract the month and day using isoformats? Suppose today is March 8, 2013.

>>> d = datetime.date.today() >>> d.month 3 >>> d.day 8 

I want to:

 >>> d = datetime.date.today() >>> d.month 03 >>> d.day 08 

I can do this by writing the operators and concatenation of the leading 0 if the day or month is one digit, but I wondered if there was an automatic way to generate what I want.

Rate the help.

+53
python datetime iso
Mar 19 '13 at 20:03
source share
2 answers

Look at the types of these properties:

 In [1]: import datetime In [2]: d = datetime.date.today() In [3]: type(d.month) Out[3]: <type 'int'> In [4]: type(d.day) Out[4]: <type 'int'> 

Both are integers. Thus, there is no automatic way to do what you want. Therefore, in a narrow sense, the answer to your question is no .

If you need leading zeros, you will have to format them anyway. To do this, you have several options:

 In [5]: '{:02d}'.format(d.month) Out[5]: '03' In [6]: '%02d' % d.month Out[6]: '03' In [7]: d.strftime('%m') Out[7]: '03' 
+86
Mar 19 '13 at 20:24
source share

you can use string formatting to populate any integer with zeros. It acts the same as C printf .

 >>> d = datetime.date.today() >>> '%02d' % d.month '03' 
+7
Mar 19 '13 at 20:14
source share



All Articles