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.
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 == None or passedArgs == None): #initiate start of week to Monday (sunday =1, monday =2, so on) startOfWeek = 2 try : startOfWeek = passedArgs except: startOfWeek = 2 WeekData = _getWeekDetails(passedArgs, passedArgs, startOfWeek) print "Monday of Week %s: %s \n" % (passedArgs, strftime("%Y-%m-%d", WeekData)) print "Sunday of Week %s: %s \n" % (passedArgs, strftime("%Y-%m-%d", WeekData))
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'