Weekdays
Building a date for the 20th of the month or for the 3rd week of the month is pretty straightforward, but what if you have to build the date for the 3rd Monday of the month?
How to do it...
Go through these steps:
- To approach this problem, we are going to actually generate all the month days that match the requested weekday:
import datetime def monthweekdays(month, weekday): now = datetime.datetime.utcnow() d = now.replace(day=1, month=month, hour=0, minute=0, second=0, microsecond=0) days = [] while d.month == month: if d.isoweekday() == weekday: days.append(d) d += datetime.timedelta(days=1) return days
- Then, once we have a list of those, grabbing the nth day is just a matter of indexing the resulting list. For example, to grab the Mondays from March:
>>> monthweekdays(3, 1)
[datetime.datetime(2018, 3, 5, 0, 0),
datetime.datetime(2018, 3, 12, 0, 0),
datetime.datetime(2018, 3, 19, 0, 0),
datetime.datetime...