How to get the number of days in a month using python ?

Published: December 17, 2020

Updated: February 19, 2023

Tags: Python; Calendar;

DMCA.com Protection Status

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 calendar

days = 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 = 2016
month = 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 date

days = (date(2014, 2+1, 1) - date(2014, 2, 1)).days

print("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 1
day 2
day 3
day 4
day 5
day 6
day 7
day 8
day 9
day 10
day 11
day 12
day 13
day 14
day 15
day 16
day 17
day 18
day 19
day 20
day 21
day 22
day 23
day 24
day 25
day 26
day 27
day 28

References