Xanatos08
Xanatos08

Reputation: 25

Is there a function in python that returns the i-th day of the week within the month?

Given a date, it is necessary to know if it corresponds to the first, second, third (etc) day of the week within the month. For example: If the entry is 2017-01-04, return: 1th Wednesday of the month. If the entry is 2017-01-25, return: 4th Wednesday of the month. If the entry is 2018-10-18, return: 3th Thursday of the month.

I've searched the datetime library but can't find any that returns that value.

Upvotes: 2

Views: 130

Answers (1)

gmds
gmds

Reputation: 19885

Use weekday:

from datetime import datetime

weekday_map = {0: 'Monday',
               1: 'Tuesday',
               2: 'Wednesday',
               3: 'Thursday',
               4: 'Friday',
               5: 'Saturday',
               6: 'Sunday'}

suffix_map = {1: 'st',
              2: 'nd',
              3: 'rd',
              4: 'th',
              5: 'th'}

def which_weekday(date):
    dt = datetime.strptime(date, '%Y-%m-%d')
    which = (dt.day - 1) // 7 + 1
    weekday = weekday_map[dt.weekday()]
    return f'{which}{suffix_map[which]} {weekday} of the month'

print(which_weekday('2017-01-04'))
print(which_weekday('2017-01-25'))
print(which_weekday('2018-10-18'))

Output:

1st Wednesday of the month
4th Wednesday of the month
3rd Thursday of the month

Upvotes: 1

Related Questions