182

Is there a way to extract month and day using isoformats? Lets assume today's date is March 8, 2013.

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

I want:

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

I can do this by writing if statements and concatenating a leading 0 in case the day or month is a single digit but was wondering whether there was an automatic way of generating what I want.

alex
  • 6,818
  • 9
  • 52
  • 103
codingknob
  • 11,108
  • 25
  • 89
  • 126

2 Answers2

285

Look at the types of those 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. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that 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'

In [8]: f'{d.month:02d}'
Out[8]: '03'
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • Thank you. For those using multiple values with manual numbering, just make sure to add the number before ":02d", e.g.: {0}/{1:02d}-{2:02d}_{3}.json'.format(othervalue, currentMonth, currentDay, othervalue2) – Alex Jul 28 '17 at 08:58
  • 9
    Just to add another formatting method to get a padded zero string you could use the `zfill()` function like so: `str(d.month).zfill(2)` – Muon Mar 01 '18 at 04:22
  • date ='2019-09-15' f'0{pd.to_datetime(date).month}' – Dheeraj Inampudi Oct 04 '19 at 14:00
  • this one `f'{d.month:02d}'` is perfect. Thx ! – Nicoolasens Feb 01 '22 at 23:37
56

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'
eduffy
  • 39,140
  • 13
  • 95
  • 92