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
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).
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 ).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With