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:
JavaScript
x
2
1
weeks2020 = [date(2020, 1, 1), date(2020, 1, 6), date(2020, 1, 13), ]
2
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:
JavaScript
1
12
12
1
from datetime import date, timedelta
2
3
START_DATE = date(2020, 1, 1)
4
INTERVAL = timedelta(weeks=1)
5
STEPS = 54
6
7
prev_date = START_DATE
8
9
for i in range(1, STEPS):
10
print(prev_date.strftime('%Y-%m-%d')) # step 1: 2020-01-01, step 2: 2020-01-08, ...
11
prev_date += INTERVAL
12
Advertisement
Answer
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.
JavaScript
1
10
10
1
START_DATE = date(2020, 1, 1)
2
INTERVAL = timedelta(weeks=1) - timedelta(days=START_DATE.weekday())
3
4
cur_date = START_DATE
5
6
while cur_date.year == START_DATE.year:
7
print(cur_date.strftime("%Y-%m-%d"))
8
cur_date += INTERVAL
9
INTERVAL = timedelta(weeks=1)
10