Determine the Number of Days in a Month with Python

Get the number of days in a specific month of a date string

In this article, we demonstrate five examples to determine the number of days for a given month in Python. Modules like calendar and datetime assist us in the following. Applications such as data validation, calculating time intervals, scheduling tasks, and financial calculations widely make use of this.

Code Implementation to Determine the Number of Days in a Month

Let’s now get right into the code implementation for determining how many days a month has.

Example 1: Using Conditional Statements

month = 12
year=2023
    
if((month==2) and ((year%4==0)  or ((year%100==0) and (year%400==0)))) :
    print("Number of days is 29");

elif(month==2) :
    print("Number of days is 28");

elif(month==1 or month==3 or month==5 or month==7 or month==8 or month==10 or month==12) :
    print("Number of days is 31");

else :
    print("Number of days is 30");

We mention the month and year in the variables month and year which we want to calculate the count of days for. Later a if elif loop is started the first if loop we calculate for a month with 29 days. (month==2) checks if the month is February since February is the only month with a different number of days in a leap year.The expression (year%4==0) or ((year%100==0) and (year%400==0)) checks if the year is divisible by 4 and either not divisible by 100 or divisible by 400. This is because a leap year occurs every 4 years, except for years that are divisible by 100 but not divisible by 400. The rest of the elif loop directly mentions the number of months and the specific output to be printed if the months are not in the range (1,3,5,7,8,10,12) then it is a 30 days month.

Output:

Example1 1

Example 2: Using the calendar Module

import calendar

month = 2   # February
year = 2023

num_days = calendar.monthrange(year, month)[1]

print("Number of days is",num_days)   

In this code we import calender module which is used when working with a calendar,it provides a function to print a calendar, determine a leap year, or calculate the number of days in a month. We specify the month and year we wish to calculate days for. To get the number of days in the month we define calender.monthrange() function. Last we print the output with a number of days.

Output:

Example2 1

Example 3: Using Calendar and Datetime modules

#Get the number of days in the current month using calendar and datetime modules
import calendar
import datetime

now = datetime.datetime.now()
month = now.month
year = now.year

num_days = calendar.monthrange(year, month)[1]

print(f"Number of days in {calendar.month_name[month]} {year}: {num_days}")

In this code we would be getting the number of days of the current month and year for that we import calender and datetime modules. We define three functions datetime.datetime.now() ,now.month() and now.year() and lastly, print the month and year with its days.

Output:

Example3 2

Example 4: Printing All Months with Their Number of Days

import calendar

year = 2023

for month in range(1, 13):
    num_days = calendar.monthrange(year, month)[1]
    print(f"{calendar.month_name[month]} {year}: {num_days} days")

Here we print all the months of the given year with their specific number of days. After importing calendar module we mention the year. We begin a for loop with the given range of months and late print the month year and days.

Output:

Example4

Example 5: Determining Days in a Month from a Date String

import calendar

date_string = "2023-02-15"
year, month, day = map(int, date_string.split("-"))

num_days = calendar.monthrange(year, month)[1]

print(f"Number of days in {calendar.month_name[month]} {year}: {num_days}")
  • In this code, we calculate the number of days in a specific month of a date string.
  • We define the date_string variable as “2023-02-15”.
  • The line year, month, day = map(int, date_string.split("-")) is used to extract the year, month, and day components from the date string in the “YYYY-MM-DD” format and convert them to integers.
  • The calendar.monthrange(year, month) function returns a tuple (weekday, num_days), where ‘weekday’ represents the weekday of the first day of the month (0 is Monday and 6 is Sunday), and ‘num_days’ is the number of days in the month.
  • By using calendar.monthrange(year, month)[1], we extract the number of days in the month from the tuple returned by the monthrange() function.

Output:

Example5

Conclusion

In this article, we demonstrated five examples in Python to determine the number of days in a given month, ranging from specifying the date to getting the current month’s data. These examples provide different approaches, including using conditional statements and the calendar module. Determining the number of days in a given month is a valuable operation that can be used in a wide variety of applications, from date validation to financial calculations.

What other ways can you implement this functionality in Python, and how can you apply this knowledge to other practical applications?

Further reading