In this article, we will learn how to find the total number of days in the given month in python.
There are many ways to get or find the total number of days in the given month in python. In this article, we find the total number of days in the given month by using date and by year and month. Here is some example as follows:
Example 1: In this example, we are using monthrange()
method to calculate the total number of days in a month by passing year and month as param values in Python.
# Import Module
from calendar import monthrange
Total_number_days = monthrange(2020, 2)[1]
print("\nTotal Number of Days in a Month: ",Total_number_days)
# Output ==> Total Number of Days in a Month: 29
Example 2: In this example, we are using a date.replace()
and datetime.timedelta()
to get the total number of days in a month and we are using a date as Param value in Python.
# Import Module
import datetime
def Total_Number_of_Days_in_Month(date):
Total_number_days = (date.replace(month = date.month % 12 +1, day = 1)-datetime.timedelta(days=1)).day
return Total_number_days
print("\nTotal Number of Days in a Month: ",Total_Number_of_Days_in_Month(datetime.datetime.now()))
# Output ==> Total Number of Days in a Month: 31
print("\nTotal Number of Days in a Month: ",Total_Number_of_Days_in_Month(datetime.datetime(2020,2,24)))
# Output ==> Total Number of Days in a Month: 29
Example 3: In this example, we will import the calendar
module and use the monthlen()
method of this module to get the total number of days in a month and pass the year and month as param value.
# Import Module
import calendar
Total_number_days=calendar.monthlen(2020, 3)
print("\nTotal Number of Days in a Month: ",Total_number_days)
# Output ==> Total Number of Days in a Month: 31
Example 4: In this example, we will use monthen()
method from calendar
module and date to get the total number of days in a month using a given date.
# Import Module
import datetime
import calendar
def Total_Number_of_Days_in_Month(date):
Total_number_days=calendar.monthlen(date.year,date.month)
return Total_number_days
print("\nTotal Number of Days in a Month: ",Total_Number_of_Days_in_Month(datetime.datetime.now()))
# Output ==> Total Number of Days in a Month: 31
print("\nTotal Number of Days in a Month: ",Total_Number_of_Days_in_Month(datetime.datetime(2020,2,24)))
# Output ==> Total Number of Days in a Month: 29
I hope this article will help you to understand how to find the total number of days in the given month in python.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments