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.
- First, let's create a function called
get_days_in_monththat takes two parameters:yearandmonth. This function will return the number of days in the given month.
def get_days_in_month(year, month):
# code goes here
- Next, let's import the
calendarmodule, which provides useful functions related to calendars.
import calendar
To get the number of days in a month, we can use the
calendar.monthrange()function. This function takes two parameters:yearandmonth, and returns a tuple containing the first weekday of the month and the number of days in the month.Inside the
get_days_in_monthfunction, we can use thecalendar.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)
- Finally, we'll return the
num_daysvariable from the function.
return num_days
- Here's the complete code for the
get_days_in_monthfunction:
import calendar
def get_days_in_month(year, month):
_, num_days = calendar.monthrange(year, month)
return num_days
- 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.