-3

Is there a way to extract all dates in a week given year and week, with the first date starting on a monday? E.g. if I provide the year "2020" and week "2", I should get

['2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09', '2020-01-10', '2020-01-11', '2020-01-12']

erikvm
  • 858
  • 10
  • 30
  • 1
    Can you explain *how* you arrived at this result, and what is preventing you from translating it into Python? – Scott Hunter Jan 08 '20 at 19:10
  • this is a dublicate : https://stackoverflow.com/questions/56163008/how-to-get-all-dates-of-week-based-on-week-number-in-python/56164212 please search before creating questions :) – marxmacher Jan 08 '20 at 19:11
  • 3
    Does this answer your question? [how to get all dates of week based on week number in python](https://stackoverflow.com/questions/56163008/how-to-get-all-dates-of-week-based-on-week-number-in-python) – marxmacher Jan 08 '20 at 19:12
  • All those answer base it on sundays as the start of the week - not monday – erikvm Jan 08 '20 at 19:12
  • @erikvm There isn't going to be a word for word chunk of code you can just directly copy and paste, adapt their code to work for your usecase. – Libra Jan 08 '20 at 19:13

2 Answers2

1

You can use the calendar module to get a list of all the weeks in a year, then simply shoose the one you want:

import calendar
from itertools import groupby

year = 2020
my_calendar = calendar.Calendar()
weeks = (w for month in range(1, 13) for w in my_calendar.monthdatescalendar(year, month))

# deduplicate the lists
weeks = [k for k, _ in groupby(weeks)]

weeks[1] 
# [datetime.date(2020, 1, 6), datetime.date(2020, 1, 7), datetime.date(2020, 1, 8), datetime.date(2020, 1, 9), datetime.date(2020, 1, 10), datetime.date(2020, 1, 11), datetime.date(2020, 1, 12)]

It's then pretty easy to change those date objects to strings in the format you want

[d.strftime("%Y-%m-%d") for d in week[1]]
# ['2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09', '2020-01-10', '2020-01-11', '2020-01-12']
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

This is almost a duplicate to this: how to get all dates of week based on week number in python

To get the week to start from monday you change 0 to 1 on this line

startdate = time.asctime(time.strptime('2019 %d 0' % WEEK, '%Y %W %w')) 

and -2 to -1 here

WEEK  = 20 - 2 # as it starts with 0 and you want week to start from sunday
marxmacher
  • 591
  • 3
  • 20