Home > Mobile >  How can I get the start and end dates for each week?
How can I get the start and end dates for each week?

Time:05-09

week = datetime.date(2022,4,10).isocalendar()[1]

After finding the week, how can I get the start and end date of the week?

CodePudding user response:

Use date.fromisocalendar, such as:

import datetime

year, week, day = datetime.date(2022, 4, 10).isocalendar()

date_first = datetime.date.fromisocalendar(year, week, 1)
date_last = datetime.date.fromisocalendar(year, week, 7)

print(date_first)
print(date_last)

CodePudding user response:

Python 3.6 version of rshepp's answer:

from datetime import datetime, date

year, week, day = date(2022, 4, 10).isocalendar()

date_first = datetime.strptime(f'{year}{week}0', '%Y%U%w')
date_last = datetime.strptime(f'{year}{week}6', '%Y%U%w')

print(date_first, date_last, sep='\n')

Output, Sunday-Saturday

2022-04-03 00:00:00
2022-04-09 00:00:00

date_first = datetime.strptime(f'{year}{week}1', '%Y%U%w')
date_last = datetime.strptime(f'{year}{week 1}0', '%Y%U%w')
print(date_first, date_last, sep='\n')

Output, Monday-Sunday

2022-04-04 00:00:00
2022-04-10 00:00:00

CodePudding user response:

Here is a simple solution with DateTime library :

from datetime import datetime, timedelta

date = '10-05-2022'
dt = datetime.strptime(date, '%d-%m-%Y')
start = dt - timedelta(days=dt.weekday())
end = start   timedelta(days=6)

print(start)
print(end)
  • Related