getYearMonthWeekRange

by @jehiah on 2007-10-25 04:03UTC
Filed under: All , Python , Programming

Sometimes I find myself needing an odd date function. This is one of those functions.

Here is what it does: you give it a year,month and week number, and it returns the start and end dates of that week.

viz. you ask for the start and end dates for the 1st week of November, It gives back 2007-11-1 and 2007-11-3

Here are a few more examples

[python]
>>>getYearMonthWeekRange(2007,10,1)
(datetime.date(2007, 10, 1), datetime.date(2007, 10, 6))

>>>getYearMonthWeekRange(2007,10,5)
(datetime.date(2007, 10, 28), datetime.date(2007, 10, 31))

>>>TMUtil.getYearMonthWeekRange(2007,11,1)
(datetime.date(2007, 11, 1), datetime.date(2007, 11, 3))
[/python]

The dates returned for week 1 are from the 1st of the month through the first Saturday. The dates of the last week are from the last Sunday till end last calendar day of the month

If the week you are requesting doesn’t exist, it will return (None,None)

[python]
import datetime
def getYearMonthWeekRange(year,month,week):
    """ returns the the start and end dates of a given week in a given month/year.  
    The dates returned for week 1 are from the 1st of the month through the first saturday. 
    The dates of the last week are from the last sunday till end last calendar day of the month """

    startDayOfMonth = datetime.date(year,month,1)
    startDay = datetime.date(year,month,1)
    startOfMonthWeek = startDay - datetime.timedelta(days=whichWeek(startDay.weekday()))
    startOfCalendarWeek = startOfMonthWeek # always true for the 1st of the month
    if week >1:
        startDay = startOfMonthWeek + datetime.timedelta(days=(week-1)*7)
        startOfCalendarWeek = startDay## we are at the start of the week

    if month == 12:
        beginningOfNextMonth = datetime.date(year+1,1,1)
    else:
        beginningOfNextMonth = datetime.date(year,month+1,1)

    endOfCalendarMonth = beginningOfNextMonth - datetime.timedelta(days=1)
    endOfCalendarWeek = startOfCalendarWeek + datetime.timedelta(days=6) ## add 6 days, not 7; you want end of week, not beginning of next week

    if startDay >= beginningOfNextMonth: ## this week # doesn't exist
        return (None, None)

    endDay = endOfCalendarWeek>=beginningOfNextMonth and endOfCalendarMonth or endOfCalendarWeek
    return (startDay,endDay)


[/python]
Subscribe via RSS ı Email
Jehiah Czebotar