how to get all dates of week based on week number in python

Question:

I want all the dates of the present week based on weeknumber.

I can get week number like

import datetime
weeknum=datetime.datetime.now().isocalendar()[1]

result is 20.

wanted all dates of week 20.
the final output should be

dates=['2019-05-12','2019-05-13','2019-05-14','2019-05-15','2019-05-16','2019-05-17','2019-05-18']

please help me.

Asked By: learningstudent

||

Answers:

I would take a look at both of the below questions. The first should help you to calculate the starting date given a week number – don’t forget to specify your year.

Get date from week number

I would then use the below answer and instead of using a start/end date, use your start date from above and add 1 day; 6 times and store each new date in an array.

Python: give start and end of week data from a given date

Answered By: tgrobinson

Use timedelta and a list comprehension.

import datetime
theday = datetime.date.today()
weekday = theday.isoweekday()
# The start of the week
start = theday - datetime.timedelta(days=weekday)
# build a simple range
dates = [start + datetime.timedelta(days=d) for d in range(7)]

To get output in strings

dates = [str(d) for d in dates]
Answered By: Will

What you can do is this –

weekdates = []
week_number = datetime.datetime.now().isocalendar()[1]
for day in range(7):
    week_date = datetime.datetime.strptime("2019-W{}".format(week_number)+ '-{}'.format(day), "%Y-W%W-%w")
    weekdates.append(week_date)

What this does is, this leverages the date format conversion to construct a date according to the day in the week.

Hope this helps.

Answered By: yadavankit

You can do it with time and datetime as well as this answer suggest but change it to your requirements:

WEEK  = 20 - 2 # as it starts with 0 and you want week to start from sunday
startdate = time.asctime(time.strptime('2019 %d 0' % WEEK, '%Y %W %w')) 
startdate = datetime.datetime.strptime(startdate, '%a %b %d %H:%M:%S %Y') 
dates = [startdate.strftime('%Y-%m-%d')] 
for i in range(1, 7): 
    day = startdate + datetime.timedelta(days=i)
    dates.append(day.strftime('%Y-%m-%d')) 

Output as following:

dates = ['2019-05-12',
         '2019-05-13',
         '2019-05-14',
         '2019-05-15',
         '2019-05-16',
         '2019-05-17',
         '2019-05-18']
Answered By: Sergey Pugach
import datetime

# Starts with knowing the day of the week
week_day=datetime.datetime.now().isocalendar()[2]

# Calculates Starting date (Sunday) for this case by subtracting current date with time delta of the day of the week
start_date=datetime.datetime.now() - datetime.timedelta(days=week_day)

# Prints the list of dates in a current week
dates=[str((start_date + datetime.timedelta(days=i)).date()) for i in range(7)]
dates

The Output is:

>>> dates
['2019-05-12', '2019-05-13', '2019-05-14', '2019-05-15', '2019-05-16', '2019-05-17', '2019-05-18']

Hope this can help you. Have a nice day. 😀

Answered By: ALFAFA

For those who need the output dates to start from a monday can tweak it like this:

import time
import datetime

WEEK  = 20 - 1 # as it starts with 0 and you want week to start from sunday
startdate = time.asctime(time.strptime('2019 %d 1' % WEEK, '%Y %W %w')) 
startdate = datetime.datetime.strptime(startdate, '%a %b %d %H:%M:%S %Y') 
dates = [startdate.strftime('%Y-%m-%d')] 
for i in range(1, 7): 
    day = startdate + datetime.timedelta(days=i)
    dates.append(day.strftime('%Y-%m-%d'))
print(dates)
Answered By: marxmacher

Take the previous 14 days, the current day, and the following 14 days as candidates. Finally, check for which date week number is similar to the current week number:

import datetime

def week_to_dates():
    date = datetime.date.today()
    week = date.strftime("%V")

    candidates = [date - datetime.timedelta(days=k) for k in range(14, 0, -1)] + 
                 [date] + 
                 [date + datetime.timedelta(days=k) for k in range(1, 15)]
    return [candidate.strftime('%Y-%m-%d') for candidate in candidates if candidate.strftime("%V") == week]
Answered By: Rajan Raju

Simply you can use python fromisocalendar() function

year = 2023
week = 12

startdate = datetime.date.fromisocalendar(year, week, 1)

dates = []
for i in range(7):
   day = startdate + datetime.timedelta(days=i)
   dates.append(day)

the output will be:

[
  "2023-03-20",
  "2023-03-21",
  "2023-03-22",
  "2023-03-23",
  "2023-03-24",
  "2023-03-25",
  "2023-03-26"
]
Answered By: Ahmed Amer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.