How can I get the previous week in Python?

tdelam picture tdelam · Oct 30, 2013 · Viewed 22k times · Source

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

Answer

Dolph picture Dolph · Oct 30, 2013

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)