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 example:
import calendar
# Get current month
_, number_of_days = calendar.monthrange(2022, 12)
print(number_of_days) # 31
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
I hope you find this useful.