Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the previous week in Python?

Tags:

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 
like image 522
tdelam Avatar asked Oct 30 '13 15:10

tdelam


People also ask

How do I get last week Monday in Python?

You can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday).

How do I get last week's startdate and Enddate in Python?

You can use datetime. timedelta for that. It has an optional weeks argument, which you can set to -1 so it will subtract seven days from the date . You will also have to subract the current date's weekday (and another one, to even the day since the Monday is 0 ).


1 Answers

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) 
like image 83
Dolph Avatar answered Oct 08 '22 21:10

Dolph