V Anon
V Anon

Reputation: 543

counting specific weekday between two dates

I am trying to make a python program that will count the day that falls on, lets say, Monday the 7th from certain day in the past to today.

Here is what I have so far.

from datetime import date


def num_day(past_Date):

    # this is the total number of specific date between the years
    sum(date(year, month, 7).weekday() == 0 
    for year in range(past_Date.year, date.today().year + 1) for month in range(1, 13))

now here's my problem

let's say the past_date is date(1945, 11, 6) and today is date(2018, 11, 6)

How can I subtract/add the excess/lack of count Monday 7th that does not exist between the actual range of dates?

This conundrum has been bugging me for hours and I can't seem to find a way out.

Upvotes: 2

Views: 163

Answers (1)

b-fg
b-fg

Reputation: 4137

I think a better approach is to iterate from the past_date until today while saving all the matches in a list. Here is how I have done it

from datetime import date
from datetime import timedelta

def num_day(past_date, my_day, my_weekday):
    dates = []
    while past_date <= date.today():
        if past_date.weekday() == my_weekday and past_date.day == my_day:
            dates.append(past_date)
        past_date = past_date + timedelta(days=1)
    return dates

def main():
    dates = num_day(past_date = date(1945, 11, 6), my_day = 7, my_weekday = 0)
    print(dates)

if __name__ == '__main__':
    main()

Remember that my_weekday has to be between 0 and 6. Otherwise use date.isoweekday() instead of date.weekday().

Upvotes: 1

Related Questions