Question
Asked By – codingknob
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.
Now we will see solution for issue: Extracting double-digit months and days from a Python date [duplicate]
Answer
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'
This question is answered By – Roland Smith
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0