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

0 Comments
Date calculation is pretty easy in Python, but to find the first/last specific day of the month may be a bit harder.
01.import calendar
02. 
03.# Get the first "day" of the month and the number of days in the month
04.month_range = calendar.monthrange(your_date.year, your_date.month)
05. 
06.if offset_position == 'first': # First Monday of the month
07.  date_corrected = datetime.date(your_date.year, your_date.month, 1)
08.  delta = (calendar.MONDAY - month_range[0]) % 7
09.  return your_date_corrected + datetime.timedelta(days = delta)
10. 
11.else: # Last Monday of the month
12.  date_corrected = datetime.date(your_date.year, your_date.month, month_range[1])
13.  delta = (your_date.weekday() - calendar.MONDAY) % 7
14.  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