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.