;

How to Get the Total Number of Mondays or Any Day of the Week in the Month in Python


Tutorialsrack 03/03/2021 Python

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. 

Example 1: Using calendar and datetime module

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.

Example 1: Using calendar and datetime module
# 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)
Output

Total Mondays in the Month:  5

Example 2: Using datetime Module and while loop

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.

Example 2: Using datetime Module and while loop
# 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)
Output

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!


Related Posts



Comments

Recent Posts
Tags