Skip to content
Related Articles

Related Articles

Improve Article

Python Program to Count date on a particular weekday in given range of Years

  • Last Updated : 06 Jun, 2021

Given a date, our task is to get the weekday index and year range, compute the total occurrence of the date on a particular weekday in the year range.

Example:

Input : date = 13, weekdy = 5, strt, end = 1950, 2020

Output : 120

Explanation : Total dates with Friday 13 from 1950 – 2020 is 120.



Input : date = 13, weekdy = 1, strt, end = 1950, 2050

Output : 173

Explanation : Total dates with Monday, 13 from 1950 – 2050 is 173.

Method 1 : Using loop + weekday()

In this, we run a nested loop from start year to end the year and within each year, each month is checked with a date to be exact weekday as required, if found, the counter is incremented.

Python3




# Python3 code to demonstrate working of
# Count date on weekday in Year Range
# Using loop + weekday()
from datetime import datetime
  
# initializing date
date = 13
  
# initializing weekday
weekdy = 5
  
# initializing range of Years
strt, end = 1950, 2020
  
# printing Number
print("The date, weekday : " + str(date) + " " + str(weekdy))
  
res = 0
for year in range(strt, end + 1):
  
    # checking each month for same date
    # weekday combination
    for month in range(1, 13):
        if datetime(year, month, date).weekday() == weekdy:
            res += 1
  
# printing result
print("Total dates with same weekday : " + str(res))

Output:

The date, weekday : 13 5
Total dates with same weekday : 120

Method 2 : Using sum() + generator expression

Similar to the above method, the only difference being generator expression is used for the task of a nested loop, sum() performs the task of summing the correct found year, month combination. 

Python3




# Python3 code to demonstrate working of
# Count date on weekday in Year Range
# Using sum() + generator expression
from datetime import datetime
  
# initializing date
date = 13
  
# initializing weekday
weekdy = 5
  
# initializing range of Years
strt, end = 1950, 2020
  
# printing Number
print("The date, weekday : " + str(date) + " " + str(weekdy))
  
# sum performs accumulation
res = sum(datetime(year, month, date).weekday() == weekdy
          for year in range(strt, end + 1) for month in range(1, 13))
  
# printing result
print("Total dates with same weekday : " + str(res))

Output:

The date, weekday : 13 5
Total dates with same weekday : 120

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :