Welcome, guest | Sign In | My Account | Store | Cart

The recipe below calculates the start date and end date of a given week of a year.

Parameters needed is the week number and year to use.

Python, 38 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env /usr/bin/python2.4

import sys
import datetime
from time import strptime, strftime

def _getWeekDetails(_weekNo, _Year, _weekStart):
    rslt = []
    janOne = strptime('%s-01-01' % _Year, '%Y-%m-%d')
    dayOfFirstWeek = ((7-int((strftime("%u",janOne)))+ int(_weekStart)) % 7)
    if dayOfFirstWeek == 0:
        dayOfFirstWeek = 7
    dateOfFirstWeek = strptime('%s-01-%s' % (_Year, dayOfFirstWeek), '%Y-%m-%d')
    dayOne = datetime.datetime( dateOfFirstWeek.tm_year, dateOfFirstWeek.tm_mon, dateOfFirstWeek.tm_mday )
    daysToGo = 7*(int(_weekNo)-1)
    lastDay = daysToGo+6
    dayX = dayOne + datetime.timedelta(days = daysToGo)
    dayY = dayOne + datetime.timedelta(days = lastDay)
    resultDateX = strptime('%s-%s-%s' % (dayX.year, dayX.month, dayX.day), '%Y-%m-%d')
    resultDateY = strptime('%s-%s-%s' % (dayY.year, dayY.month, dayY.day), '%Y-%m-%d')
    rslt.append(resultDateX)
    rslt.append(resultDateY)
    return rslt

if __name__ == '__main__':
    passedArgs = sys.argv
    if not (passedArgs[1] == None or passedArgs[2] == None):

        #initiate start of week to Monday (sunday =1, monday =2, so on)
        startOfWeek = 2
        try :
            startOfWeek = passedArgs[3]
        except:
            startOfWeek = 2

        WeekData = _getWeekDetails(passedArgs[1], passedArgs[2], startOfWeek)
        print "Monday of Week %s: %s \n" % (passedArgs[1], strftime("%Y-%m-%d", WeekData[0]))
        print "Sunday of Week %s: %s \n" % (passedArgs[1], strftime("%Y-%m-%d", WeekData[1]))

I am working on several reports that requires me to calculate the dates of the a given week number in a year. I am using to for other reporting tools and queries to supply me with the dates that I need.

Currently, the recipe requires two parameters and an another optional parameter. The first parameter is the given week number. Second is the year to use. The third and the optional parameter is the day of week to use as the first day of the week. Default is set to Monday.

Using the recipe, i.e. you passed the parameters 1 2007 it will give you the dates of the first week in the year of January which is 2007-01-01 and the last day of that week which is 2007-01-07.

Passing a week number greater than 52 would result to the (52 - x)th week where x is the passed parameter.

Note that This will calculate the first week of the given year (starting on the specified day) belonging to that year. i.e. parameters "1 2004" results to '2004-01-05' and '2004-01-11'

8 comments

Chris Arndt 14 years, 5 months ago  # | flag

Description missing "week" The recipe below calculates the start date and end date of a given week of a year.

Tzury Bar Yochay 14 years, 5 months ago  # | flag

Get the same with 5 lines of code. from datetime import date, timedelta

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

Tzury Bar Yochay 14 years, 5 months ago  # | flag

Get the same with 5 lines of code.

from datetime import date, timedelta

def foo(year, week):
    d = date(year,1,1)
    dlt = timedelta(days = (week-1)*7)
    return d + dlt,  d + dlt + timedelta(days=6)
Jojbon Paul Mark Lee (author) 14 years, 5 months ago  # | flag

First week of the given year. First week of the given year does not necessarily start with January 1 a s its starting date.

Tzury Bar Yochay 14 years, 5 months ago  # | flag

You are right! However here is a fix.

def foo(year, week):
    d = date(year,1,1)
    d = d - timedelta(d.weekday())
    dlt = timedelta(days = (week-1)*7)
    return d + dlt,  d + dlt + timedelta(days=6)
Jojbon Paul Mark Lee (author) 14 years, 5 months ago  # | flag

Cool function! That simplifies my function a lot! I need to alter it though, I need the first week of the given year, if I pass 2004 1 to your function it returns "2003-12-29 , 2004-01-04" my expected result is "2004-01-05 , 2004-01-11". Thanks for the coding idea, it makes my codes a lot shorter!

petr.bunka 13 years ago  # | flag

Great! But years with January the 1st on Friday, Saturday or Sunday have 1week on next week - http://en.wikipedia.org/wiki/Week. So another fix for foo function (I renamed it to get_week_days:-)) is:

from datetime import date, timedelta

def get_week_days(year, week):
    d = date(year,1,1)
    if(d.weekday()>3):
        d = d+timedelta(7-d.weekday())
    else:
        d = d - timedelta(d.weekday())
    dlt = timedelta(days = (week-1)*7)
    return d + dlt,  d + dlt + timedelta(days=6)
Padmaksha 8 years, 6 months ago  # | flag

Hi Can anyone tell me that insted of year,week format of input if i want year, month, week what will be the code for that. That is in input i want the year, month and week given eg, what is the start date of the first week of the third month of a given year. Any help will be highly appreciated as i am in the middle of a project. Thanks in advance