Note: The OP says in the comments, "I was looking for the past Monday". I take this to mean we are looking for the last Monday that occurred strictly before today.
The calculation is a little difficult to get right using only the datetime
module (especially given the above interpretation of "past Monday" and if you wish to avoid clunky if-statements
). For example, if today
is a Monday such as 2013-12-23
,
today - DT.timedelta(days=today.weekday())
returns 2013-12-23
, which is the same day as today
(not the past Monday).
The advantage of using the dateutil module is that you don't have to do tricky mental calculations nor force the reader to do the same to get the right date. dateutil
does it all for you:
import dateutil.relativedelta as rdelta
import datetime as DT
today = DT.date(2013, 12, 23) # Monday
past_monday = today + rdelta.relativedelta(days=-1, weekday=rdelta.MO(-1))
print(past_monday)
# 2013-12-16
next_monday = today + rdelta.relativedelta(days=1, weekday=rdelta.MO(+1))
print(next_monday)
# 2013-12-30
Note that days=-1
is needed to guarantee that past_monday
is a different day than today
.