Home > Net >  How to get Monday and Sunday of last week
How to get Monday and Sunday of last week

Time:11-29

If today is November 28, 2021, I want to get last week's Monday and Sunday like:

Monday: 2021-11-15
Sunday: 2021-11-21

I tried like this:

today = datetime.date.today()
idx = (today.weekday()   1) % 7
self.monday = (today - datetime.timedelta(7   idx - 1)).strftime('%Y-%m-%d')
self.sunday = (today - datetime.timedelta(7   idx - 7)).strftime('%Y-%m-%d')

But the output is like this, which is wrong:

Monday: 2021-11-22
Sunday: 2021-11-28  

It is correct if today's date is November 29, 2021.

How will I be able to achieve this?

CodePudding user response:

Take today's date and subtract 1 week plus today's weekday 'number':

today = datetime.date.today()
today - datetime.timedelta(days=today.weekday(), weeks=1)

For the Sunday before that, use days=today.weekday() 1

  • Related