Home > Net >  using week number to get range of dates with sunday as first day of week in python
using week number to get range of dates with sunday as first day of week in python

Time:08-27

input: week_number = 34 (or 2022-34)

expected output: ["2022-08-21","2022-08-22", "2022-08-23","2022-08-24","2022-08-25","2022-08-26","2022-08-27"]

First date should be of Sunday the last date should be Saturday work with both leap and non leap year

CodePudding user response:

Try:

import datetime

week_number = 34
out = []

date = datetime.datetime.strptime(f"2022-{week_number}-0", "%Y-%U-%w")
for day in range(7):
    out.append((date   datetime.timedelta(days=day)).strftime("%Y-%m-%d"))

print(out)

Prints:

[
    "2022-08-21",
    "2022-08-22",
    "2022-08-23",
    "2022-08-24",
    "2022-08-25",
    "2022-08-26",
    "2022-08-27",
]

From the reference:

%U - Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.

  • Related