2
votes

how to get the last week start date and end date based on date in current week scrapy (Monday - Sunday)

Example: if date is 04-feb-15, then result should be start_date = Monday(26-jan-1015) end_date = Sunday(1-feb-15)

if date is 27-feb-15, , then result should be start_date = Monday(16-feb-1015) end_date = (22-feb-15)

I have trying this:

date =aaa.xpath('xxx')
if date < datetime.datetime.today():
1

1 Answers

5
votes

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).

import datetime

def previous_week_range(date):
    start_date = date + datetime.timedelta(-date.weekday(), weeks=-1)
    end_date = date + datetime.timedelta(-date.weekday() - 1)
    return start_date, end_date

previous_week_range(datetime.date(2015, 2, 9))  # 2015-02-02, 2015-02-08
previous_week_range(datetime.date(2015, 2, 13))  # 2015-02-02, 2015-02-08
previous_week_range(datetime.date(2015, 2, 16))  # 2015-02-09, 2015-02-15