how to get list of all weeks

i tried something like this

year, week_num, day_num = date.today().isocalendar()
weeks = []
week_range_start = 1
week_range_end = 17
for i in range(week_range_start,week_range_end):
  curr_week = week_num - i
  str_week = str(curr_week) if len(str(curr_week)) == 2 else f'0{curr_week}'
  weeks.append(str(year) + str_week)
print(weeks)

my output looks something like this

['202114', '202113', '202112', '202111', '202110', '202109', '202108', '202107', '202106', '202105', '202104', '202103', '202102', '202101', '202100', '2021-1']

this is wrong because there is no 00 week number. week number starts from 1 to 52 and i also getting same 2021 instead of 2020. the output should be

['202114', '202113', '202112', '202111', '202110', '202109', '202108', '202107', '202106', '202105', '202104', '202103', '202102', '202101', '202053', '202052']

and so on if it is a leap year also it should work by changing the range and also need to parameterize the length of the range

Answer

Original Question:

I think the problem stems from working with int outputs of .isocalendar() instead of working inside of datetime objects which handle some of these issues.

Here is an example that subtracts off a week at a time using datetime.timedelta(weeks=1):

from datetime import date, timedelta

today = date.today()
weeks = []

for i in range(16):
    # Subtract a week from the initial 'today'
    today -= timedelta(weeks=1)

    # This handles some formatting to make it consistent with expected output:
    year, week, _ = today.isocalendar()
    weeks.append(str(year) + "{0:02d}".format(week))

print(weeks)

Expected output:

['202114', '202113', '202112', '202111', '202110', '202109', '202108', '202107', '202106', '202105', '202104', '202103', '202102', '202101', '202053', '202052']

Modified Question:

The question changed to focus on how to get a ‘list of dates between a start and end number‘, where start and end are a number of weeks.

To do this: you can first subtract off the number of start weeks; then loop through the remaining weeks between range(start, end), subtracting off one week at a time.

from datetime import date, timedelta


def get_list_of_weeks(start, end):

    today = date.today()
    today -= timedelta(weeks=start)

    weeks = []
    for _ in range(start, end):
        today -= timedelta(weeks=1)

        # This handles some formatting to make it consistent with expected output:
        year, week, _ = today.isocalendar()
        weeks.append(str(year) + "{0:02d}".format(week))

    return weeks


if __name__ == "__main__":
    print(list_of_weeks(10, 17))

Expected output:

['202104', '202103', '202102', '202101', '202053', '202052', '202051']