Python provides an inbuilt calendar module which allows us to determine the number of days in a month
Using python calendar module and monthrange
Python provides an inbuilt calendar module which allows us to determine the number of days in a month. We can use calendar.monthrange() function to get the number of days in a month.
The syntax for this function is: calendar.monthrange(year, month). The year and month parameters must be valid integers, where the month ranges between 1 and 12. The function returns a tuple containing two values:
The first value is the weekday of the first day of the month (0 is Monday, 6 is Sunday).
The second value is the number of days in that particular month.
For example, if we want to know the number of days in February 2014 we can use:
import calendardays = calendar.monthrange(2014, 2)[1]print("Number of days in February 2014 is "+str(days))
this code gives
Number of days in February 2014 is 28
Note that the output of calendar.monthrange(2014, 2) is (5, 28). This means that the first day of the month is a Saturday and the month has 28 days in it.
Another example
year = 2016month = 2
then
print( 'Number of days: {}'.format( monthrange(year, month)[1] ) )
returns
Number of days: 29
Using datetime
We can also use datetime module to get the number of days as follows:
from datetime import datedays = (date(2014, 2+1, 1) - date(2014, 2, 1)).daysprint("Number of days in February 2014 is "+str(days))
The output will be:
Number of days in February 2014 is 28
Loop through the days of any given month
It is then possible to use it to create a simple for loop to go through all days in a given month:
for i in range(1,calendar.monthrange(2014, 2)[1]+1):print( 'day {}'.format(i) )
the output will be:
day 1day 2day 3day 4day 5day 6day 7day 8day 9day 10day 11day 12day 13day 14day 15day 16day 17day 18day 19day 20day 21day 22day 23day 24day 25day 26day 27day 28
References
| Links | Site |
|---|---|
| calendar.monthrange(year, month) | docs.python.org |
| datetime — Basic date and time types | docs.python.org |
