Getting start/end dates given week-number
wittempj@hotmail.com
martin.witte at gmail.com
Fri Jun 9 10:24:07 EDT 2006
see the calendar faq http://www.faqs.org/faqs/calendars/faq/part3/,
look especially in section 6.7.
Tim Chase wrote:
> I've been trying to come up with a good algorithm for determining
> the starting and ending dates given the week number (as defined
> by the strftime("%W") function).
>
> My preference would be for a Sunday->Saturday range rather than a
> Monday->Sunday range. Thus,
>
> >>> startDate, stopDate = weekBoundaries(2006, 23)
>
> would yield a start-date of June 4, 2006 and an end-date of June
> 10, 2006 in this hypothetical function (as strftime("%W") for
> today, June 9th, 2006 returns 23).
>
> I've posted my first round of code below, but I'm having problems
> with dates early in 2005, as the tests show.
>
> Any thoughts/improvements/suggestions would be most welcome.
>
> Thanks,
>
> -tkc
>
>
> from datetime import date, timedelta
> from time import strptime
> DEBUG = False
> tests = [
> #test date start end
> (date(2006,1,1), (date(2006,1,1), date(2006,1,7))),
> (date(2006,1,2), (date(2006,1,1), date(2006,1,7))),
> (date(2006,1,3), (date(2006,1,1), date(2006,1,7))),
> (date(2006,1,4), (date(2006,1,1), date(2006,1,7))),
> (date(2006,1,5), (date(2006,1,1), date(2006,1,7))),
> (date(2006,1,6), (date(2006,1,1), date(2006,1,7))),
> (date(2006,1,7), (date(2006,1,1), date(2006,1,7))),
> (date(2006,1,8), (date(2006,1,8), date(2006,1,14))),
> (date(2005,1,1), (date(2004,12,26), date(2005,1,1))),
> (date(2005,1,2), (date(2005,1,2), date(2005,1,8))),
> ]
> def weekBoundaries(year, week):
> startOfYear = date(year, 1, 1)
> now = startOfYear + timedelta(weeks=week)
> # isoweekday() % 7 returns Sun=0 ... Sat=6
> sun = now - timedelta(days=now.isoweekday() % 7)
> sat = sun + timedelta(days=6)
> if DEBUG:
> print "DEBUG: now = %s/%s" % (now, now.strftime("%a"))
> print "DEBUG: sun = %s/%s" % (sun, sun.strftime("%a"))
> print "DEBUG: sat = %s/%s" % (sat, sat.strftime("%a"))
> return sun, sat
>
> for test, expectedResult in tests:
> print "Testing %s" % test
> year = test.year
> # jigger it so that %W is Sun->Sat rather than Mon->Sun
> weekNum = int((test + timedelta(days=1)).strftime("%W")) - 1
> results = weekBoundaries(year, weekNum)
> passed = (expectedResult == results)
> print "Week#%s: %s" % (weekNum, passed)
> print "=" * 50
More information about the Python-list
mailing list