28

I am currently getting the current week starting on Monday and ending on Sunday but how can I get the previous week starting on Monday and ending on Sunday? Here is what I have now for the current week:

>>> import datetime
>>> today = datetime.date.today()
>>> weekday = today.weekday()
>>> start_delta = datetime.timedelta(days=weekday)
>>> start_of_week = today - start_delta
>>> week_dates = []
>>> for day in range(7):
...     week_dates.append(start_of_week + datetime.timedelta(days=day))
...
>>> week_dates
[datetime.date(2013, 10, 28), datetime.date(2013, 10, 29), datetime.date(2013, 10, 30),     datetime.date(2013, 10, 31), datetime.date(2013, 11, 1), datetime.date(2013, 11, 2), datetime.date(2013, 11, 3)]
>>> week_dates[0], week_dates[-1]
(datetime.date(2013, 10, 28), datetime.date(2013, 11, 3)) <--- Monday, Sunday
3

1 Answer 1

47

Just add weeks=1 to your start_delta to subtract an additional week:

>>> start_delta = datetime.timedelta(days=weekday, weeks=1)

So, for today (Wednesday, October 30, 2013), start_delta will be 9 days (back to last Monday, October 21, 2013).

>>> start_delta
datetime.timedelta(9)
>>> start_of_week = today - start_delta
>>> start_of_week
datetime.date(2013, 10, 21)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.