Skip to main content

How to get the number of days in a given month in Python

How to get the number of days in a given month in Python.

Here's a step-by-step tutorial on how to get the number of days in a given month in Python.

  1. First, let's create a function called get_days_in_month that takes two parameters: year and month. This function will return the number of days in the given month.
def get_days_in_month(year, month):
# code goes here
  1. Next, let's import the calendar module, which provides useful functions related to calendars.
import calendar
  1. To get the number of days in a month, we can use the calendar.monthrange() function. This function takes two parameters: year and month, and returns a tuple containing the first weekday of the month and the number of days in the month.

  2. Inside the get_days_in_month function, we can use the calendar.monthrange() function to get the number of days in the given month. We'll assign the result to a variable called _, num_days.

_, num_days = calendar.monthrange(year, month)
  1. Finally, we'll return the num_days variable from the function.
return num_days
  1. Here's the complete code for the get_days_in_month function:
import calendar

def get_days_in_month(year, month):
_, num_days = calendar.monthrange(year, month)
return num_days
  1. Now, let's test our function by calling it with different inputs:
print(get_days_in_month(2021, 1))  # Output: 31
print(get_days_in_month(2021, 2)) # Output: 28
print(get_days_in_month(2020, 2)) # Output: 29 (leap year)
print(get_days_in_month(2021, 3)) # Output: 31
print(get_days_in_month(2021, 4)) # Output: 30

That's it! You now know how to get the number of days in a given month in Python using the calendar module. You can use the get_days_in_month function in your code whenever you need to calculate the number of days in a specific month.