user1802693 user1802693 - 6 months ago 32
Python Question

How to get the Nth occurrence of a day of the week for a given month?

The week of month does not define this value.
The shift between the starting week and starting month causes the problem in most cases.

Is there any python lib or algorithm to calculate this value?

Answer

You can calculate this by looping over the days of the month and counting whether you've come across that nth weekday:

import datetime

def get_n_weekday(year, month, day_of_week, n):
    count = 0
    for i in xrange(1, 32):
        try:
            d = datetime.date(year, month, i)
        except ValueError:
            break
        if d.isoweekday() == day_of_week:
            count += 1
        if count == n:
            return d
    return None

For example: get_n_weekday(2016, 1, 1, 1) = first Monday of January 2016 which is datetime.date(2016, 1, 4).

This uses date.isoweekday() which means Monday is 1 and Sunday is 7.

Comments