N
N
Ninzalo2022-04-03 21:50:16
Python
Ninzalo, 2022-04-03 21:50:16

How to get a list of dates in a week?

Hello,
the task is this: get a list of dates in a week
input example: "2022-4-3"
output example: [2022-4-28, 2022-4-29, 2022-4-30, 2022-4-31, 2022- 4-1, 2022-4-2, 2022-4-3]
what is the fastest and most efficient way to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Krostelev, 2022-04-04
@twistfire92

If it is convenient to enter dates as '2022-04-03', i.e. in ISO format, you can do this:

import calendar
import datetime

def weekdays(input_day):
  my_day = datetime.date.fromisoformat(input_day)
  c = calendar.Calendar()
  for week in c.monthdatescalendar(2022, 4):
      if my_day in week:
      	return[f'{weekday.year}-{weekday.month}-{weekday.day}' for weekday in week]

print(weekdays('2022-04-03'))

If the moment with the input format is important, then the line
my_day = datetime.date.fromisoformat(input_day)
can be replaced with
year, month, day = map(int, input_day.split('-'))
my_day = datetime.date(year, month, day)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question