0

I want to know the N-th time a weekday is occurring inside a given month, based on ( Date , Week day, Month and Year ).

I looked at similar questions:

How can I get the 3rd Friday of a month in Python?

The solutions for that question only concentrate on 3rd friday, but I want to be able to generalize it all week days and get the n-th time they are repeating in a month.

I also checked:

How do I get the day of week given a date in Python?

Count of weekdays in a given month

But they don't align exactly with what I'm looking for.

Ex: Given a date ( 1, Tuesday , October, 2019 ), the program should return 1, because it's the first Tuesday of the month; similarly ( 12, Saturday, October , 2019 ) should return 2 as it's second Saturday of the month.

Any help is appreciated. TIA.

Amith Adiraju
  • 306
  • 4
  • 18

2 Answers2

2

This is actually very straightforward and requires simply knowing the day of the month. If the date is the 12th of October and it's a Saturday, then it must be the second Saturday because to be the third or more Saturday, there would have to be 14 or more days before it in the month, and to be the first Saturday there would have to be fewer than 7 days before it in the month.

The calculation is as simple as (day_of_month - 1) // 7 + 1 to work out how many multiples of 7 days occur before day_of_month, and then add 1. The // operator is integer division, rounding down.

kaya3
  • 47,440
  • 4
  • 68
  • 97
1

Here's a calculation if you want to know the nth weekday of a month:

from datetime import datetime

# n 1-5 (1st-5th weekday)
# weekday 0-6 (0=Monday)
# month 1-12

def nth_weekday(n,weekday,month,year):

    if not 1 <= n <= 5:
        raise ValueError('n must be 1-5')
    if not 0 <= weekday <= 6:
        raise ValueError('weekday must be 0-6')
    if not 1 <= month <= 12:
        raise ValueError('month must be 1-12')

    # Determine the starting weekday of the month.
    start = datetime(year,month,1)
    startwday = start.weekday()

    # Compute the offset to the Nth weekday.
    day = (weekday -startwday) % 7 + 7 * (n - 1) + 1

    target = datetime(year,month,day)

    if   n == 1: postfix = 'st'
    elif n == 2: postfix = 'nd'
    elif n == 3: postfix = 'rd'
    else:        postfix = 'th'

    return f'The {n}{postfix} {target:%A} is {target:%B %d, %Y}.'


print(nth_weekday(1,4,11,2019))
print(nth_weekday(4,5,12,2019))
print(nth_weekday(4,3,1,2019))

Output:

The 1st Friday is November 01, 2019.
The 4th Saturday is December 28, 2019.
The 4th Thursday is January 24, 2019.
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251