10

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.

thrashr888
  • 1,477
  • 1
  • 17
  • 24
Andrew Ephron
  • 101
  • 1
  • 3
  • possible duplicate: http://stackoverflow.com/questions/304256/whats-the-best-way-to-find-the-inverse-of-datetime-isocalendar – sk1p Jun 04 '15 at 23:46
  • The [Doomsday Algorithm](http://en.wikipedia.org/wiki/Doomsday_rule) might be of interest to you. For example to calculate the "doomsday" for a certain year, you can just use the following function: ``doomsday = lambda y: (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7``. – pzp Jun 05 '15 at 00:47
  • Possible duplicate of [Howto calculate first date of week and last date for week in python](http://stackoverflow.com/questions/10908499/howto-calculate-first-date-of-week-and-last-date-for-week-in-python) – anthony sottile May 02 '17 at 18:22

3 Answers3

4

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

koala
  • 119
  • 8
4

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)
Suhas_Pote
  • 3,620
  • 1
  • 23
  • 38
-1
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)
Rahul
  • 717
  • 9
  • 16