In this article, you will learn how to get the total number of Mondays or any other day of the week in the month in python. There are various ways to get the total number of Mondays or any other weekdays in the month in python.
Here are the examples to get the total number of Mondays or any other weekdays in the month in python.
In this example, we used the calendar.monthcalendar()
method from the calendar module and for the current DateTime, we used the datetime
module. In this example, we find the total number of Mondays in the month but you can also find the total number of any other weekdays in the month. You have to replace the index of the array from 0 to 6. For example,
For Monday, we used i[0]
, for Tuesday, we can use i[1]
, for Wednesday, we can use i[2]
, and so on and the same way you can replace the index value for any other weekdays.
Here is the example to get the total number of Mondays in the month or any other weekdays.
# Import Module
import calendar
from datetime import datetime
TotalMondays = len([1 for i in calendar.monthcalendar(datetime.now().year,
datetime.now().month) if i[0] != 0])
# print Output
print("Total Mondays in the Month: ",TotalMondays)
Total Mondays in the Month: 5
In this example, we used the datetime
module for the current DateTime. In this example, we find the total number of Mondays in the month but you can also find the total number of any other weekdays in the month. You have to assign day.weekday()
value from 0 to 6. For example, For Monday, we used day.weekday() == 0:
, for Tuesday, we can use day.weekday() == 1:
, for Wednesday, we can use day.weekday() == 2:
, and so on and the same way you can assign day.weekday()
value for any other weekdays.
Here is the example to get the total number of Mondays in the month or any other weekdays.
# Import Module
import datetime
today = datetime.date.today()
day = datetime.date(today.year, today.month, 1)
single_day = datetime.timedelta(days=1)
TotalMondays = 0
while day.month == today.month:
if day.weekday() == 0:
TotalMondays += 1
day += single_day
# Print Output
print ("Total Mondays in the Month: ", TotalMondays)
Total Mondays in the Month: 5
I hope this article will help you to understand how to get the total number of Mondays or any other day of the week in the month in python.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments