Find Monday's date with Python

Solution 1:

>>> import datetime
>>> today = datetime.date.today()
>>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
datetime.date(2009, 10, 26)

Some words of explanation:

Take todays date. Subtract the number of days which already passed this week (this gets you 'last' monday). Add one week.

Edit: The above is for 'next monday', but since you were looking for 'last monday' you could use

today - datetime.timedelta(days=today.weekday())

Solution 2:

ChristopheD's post is close to what you want. I don't have enough rep to make a comment :(

Instead of (which actually gives you the next upcoming monday):

>>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
datetime.date(2009, 10, 26)

I would say:

>>> last_monday = today - datetime.timedelta(days=today.weekday())

If you want the previous week, add the 'weeks=1' parameter.

This makes the code more readable since you are subtracting a timedelta. This clears up any confusion caused by adding a timedelta that has negative and positive offsets.

Solution 3:

I think the easiest way is using python-dateutil like this:

from datetime import date
from dateutil.relativedelta import relativedelta, MO

today = date.today()
last_monday = today + relativedelta(weekday=MO(-1))
print last_monday