If you need to get the number of days in a month in Python, you can do that quite quickly.

We are going to do that using the calendar module.

First, import the calendar module and then call the method monthrange() which returns the first_day and also the number_of_days in a month.

Let us see this in action:

 import calendar
 ​
 # Get current month
 _, number_of_days = calendar.monthrange(2023, 2)
 ​
 print(number_of_days)  # 28

We can use this method to even check whether a year is a leap year or not:

 import calendar
 ​
 # Get current month
 year = 2023
 ​
 while True:
     _, number_of_days = calendar.monthrange(year, 2)
 ​
     if number_of_days == 29:
         print("February has 29 days in {}".format(year))
         break
 ​
     year += 1

That’s basically it.

I hope you find this useful.