Python: Calculate the first/last Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday of the Month

Date calculation is pretty easy in Python, but to find the first/last specific day of the month may be a bit harder.
import calendar

# Get the first "day" of the month and the number of days in the month
month_range = calendar.monthrange(your_date.year, your_date.month)

if offset_position == 'first': # First Monday of the month
date_corrected = datetime.date(your_date.year, your_date.month, 1)
delta = (calendar.MONDAY - month_range[0]) % 7
return your_date_corrected + datetime.timedelta(days = delta)

else: # Last Monday of the month
date_corrected = datetime.date(your_date.year, your_date.month, month_range[1])
delta = (your_date.weekday() - calendar.MONDAY) % 7
return your_date_corrected - datetime.timedelta(days = delta)

The snippet above will find the first or last Monday in the year/month given in "your_date". Throw it into a reusable function and you won't have to look at this problem again.
2n8n0x0
Now for more important things in life.

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog