Find the Friday of previous/last week in python

Assuming day is a datetime.date or datetime.datetime object, this code creates a datetime/date object for last week's friday:

friday = day - timedelta(days=day.weekday()) + timedelta(days=4, weeks=-1)

Explanation: timedelta(days=day.weekday()) is the offset between monday and day so adding 4 days and subtracting one week will get you last week's friday.

Of course you can simplify this (+4d -1w = -3d):

friday = day - timedelta(days=day.weekday() + 3)

Note: To get timedelta, use from datetime import timedelta or just import datetime and use datetime.timedelta


An another and easier way is to use python-dateutil. To get the previous Friday :

>>> from dateutil.relativedelta import relativedelta, FR
>>> from datetime import datetime
>>> datetime(2015, 7, 8) + relativedelta(weekday=FR(-1))
datetime.datetime(2015, 7, 3, 0, 0)

And the next Friday :

>>> datetime(2015, 7, 8) + relativedelta(weekday=FR(+1))
datetime.datetime(2015, 7, 10, 0, 0)