Search code examples
pythonpython-3.xdatetimecalendarweek-number

Getting all starting dates of year 2020 with ISO week frequency


I'd like to create a list of dates each of which represents the starting date of ISO week N of year 2020.

Something like:

weeks2020 = [date(2020, 1, 1), date(2020, 1, 6), date(2020, 1, 13), ...]

I have obtained something similar using timedelta(weeks=1), and adding this to my START_DATE (date(2020, 1, 1)), but the dates I obtain are not correct.

I know I could simply change my START_DATE to be date(2019, 12, 30), but I would like to know if there is a more robust approach to derive all the week starting dates present in a given year.

Just for the sake of clarity, here is what i am doing now:

from datetime import date, timedelta

START_DATE = date(2020, 1, 1)
INTERVAL = timedelta(weeks=1)
STEPS = 54

prev_date = START_DATE

for i in range(1, STEPS):
    print(prev_date.strftime('%Y-%m-%d')) # step 1: 2020-01-01, step 2: 2020-01-08, ...
    prev_date += INTERVAL

Solution

  • For the first interval, find the weekday of the starting date and subtract this from a full week. After the first step, set the interval back to one week.

    START_DATE = date(2020, 1, 1)
    INTERVAL = timedelta(weeks=1) - timedelta(days=START_DATE.weekday())
    
    cur_date = START_DATE
    
    while cur_date.year == START_DATE.year:
        print(cur_date.strftime("%Y-%m-%d"))
        cur_date += INTERVAL
        INTERVAL = timedelta(weeks=1)