Andrew Ephron
Andrew Ephron

Reputation: 101

Get start date and end date of the week, given week number and year

How do I get the start date and end date of the week, given week number and year in python?

I've tried this:

def get_start_end_dates(year, week):

     dlt = timedelta(days = (week - 1) * 7)
     d = date(year, 1, 1)
     return d + dlt, d + dlt + timedelta(days=6)

But with this function I assume that first week of the year starts with Monday.

Upvotes: 10

Views: 9763

Answers (3)

Suhas_Pote
Suhas_Pote

Reputation: 4560

Simplest (alternative) solution

First install the isoweek package

pip install isoweek

from isoweek import Week

w = Week(2021, 1)

print ("Week %s starts on %s" % (w, w.monday()))
print ("Week %s ends on %s" % (w, w.sunday()))

Output:

Week 2021W01 starts on 2021-01-04
Week 2021W01 ends on 2021-01-10

Bonus:

If you need to apply this function to pandas dataframe

df["start_of_wk"] = df.apply(lambda x: Week(x['Year'], x['wk_of_the_year']).monday(), axis=1)

df["end_of_wk"] = df.apply(lambda x: Week(x['Year'], x['wk_of_the_year']).sunday(), axis=1)

Upvotes: 4

Rahul
Rahul

Reputation: 767

import datetime
import time

 def getDateRangeFromWeek(p_year,p_week):

    firstdayofweek = datetime.datetime.strptime(f'{p_year}-W{int(p_week )- 1}-1', "%Y-W%W-%w").date()
    lastdayofweek = firstdayofweek + datetime.timedelta(days=6.9)
    return firstdayofweek, lastdayofweek


#Call function to get dates range 
firstdate, lastdate =  getDateRangeFromWeek('2019','2')

print('print function ',firstdate,' ', lastdate)

Upvotes: -1

koala
koala

Reputation: 119

I have fixed your function:

def get_start_end_dates(year, week):
     d = date(year,1,1)
     if(d.weekday()<= 3):
         d = d - timedelta(d.weekday())             
     else:
         d = d + timedelta(7-d.weekday())
     dlt = timedelta(days = (week-1)*7)
     return d + dlt,  d + dlt + timedelta(days=6)

It gets the correct start and end day of the week in given year.

It also assumes that years with first day of the year on Friday, Saturday or Sunday have 1 week on next week. See here: http://en.wikipedia.org/wiki/Week

Upvotes: 4

Related Questions