473,765 Members | 2,024 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting start/end dates given week-number

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,2 6), 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


Jun 9 '06 #1
3 16686
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,2 6), 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


Jun 9 '06 #2
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).
I think you missed %U format, since later you write:
My preference would be for a Sunday->Saturday range rather than a
Monday->Sunday range. Thus, Any thoughts/improvements/suggestions would be most welcome.


If you want to match %U:

def weekBoundaries( year, week):
startOfYear = date(year, 1, 1)
week0 = startOfYear - timedelta(days= startOfYear.iso weekday())
sun = week0 + timedelta(weeks =week)
sat = sun + timedelta(days= 6)
return sun, sat

Jun 9 '06 #3
> I think you missed %U format, since later you write:

correct. I remember seeing something (a long while back) that
had a Sunday-first format, but I must have missed it in my
reading of "man strftime".
If you want to match %U:

def weekBoundaries( year, week):
startOfYear = date(year, 1, 1)
week0 = startOfYear - timedelta(days= startOfYear.iso weekday())
sun = week0 + timedelta(weeks =week)
sat = sun + timedelta(days= 6)
return sun, sat


Works wonderfully...T hanks!

-tkc


Jun 9 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2334
by: Dave Griffiths | last post by:
Hi I am trying to get JS to work out week numbers for given dates, I'm sure this is possible. Any help would be welcomed at this point. Thanks in advance.
5
3304
by: Bullschmidt | last post by:
If I know the week number and the year, how can I calc the beginning and ending dates of the week? For background I'm going to do some grouping by week but don't just want to call the weeks Week 25, Week 26, Week 27, etc. Thanks in advance, J. Paul Schmidt, Freelance Web and Database Developer http://www.Bullschmidt.com Access Database Sample, Web Database Sample, ASP Design Tips
6
2464
by: Bill R via AccessMonster.com | last post by:
I have a query: SELECT tblCalendar.CalendarDay AS LastSunday FROM tblCalendar WHERE (((tblCalendar.CalendarDay)>=(Now()-7) And (tblCalendar.CalendarDay) <DateAdd("d",8-Weekday((Now()-7),2),(Now()-7))) AND ((tblCalendar.Weekday)=1)) ; tblCalendar is a table of consecutive dates from 1998 thru 2020. It has proven useful in many applications. CalendarDay is the date. The code above
0
2864
by: Lee Harr | last post by:
I wrote a function to return the first date of a given week (and a few related functions) : -- return the first date in the given week CREATE or REPLACE FUNCTION week_start(integer, integer) RETURNS date AS ' DECLARE pyear ALIAS FOR $1; pweek ALIAS FOR $2;
2
4221
by: MSK | last post by:
Hi, Continued to my earlier post regaring "Breakpoints are not getting hit" , I have comeup with more input this time.. Kindly give me some idea. I am a newbie to .NET, recently I installed .NET. I could not debug using breakpoints, breakpoints are not getting hit, but the application is working fine with out any issue.
5
359
by: Elainie | last post by:
I need to get the dates between now and next week but using Now and Next week not any specific dates... Please help, going mad... Elaine
2
1597
by: egrill | last post by:
I need to be able to group date field by week. I can identify the week but I need to translate the ww into a date. For example; if the date falls in the 5th week of the year, I want to group all the dates that fall in week (jan 28 though the Jan 31) all together. Does anyone have work around solution or know what functions I could use in a query or report. I have done with using the Monthname function but can't find a similar function for...
5
2517
by: cla | last post by:
I'm using this code on an application to track football schedules: ---- $season = '2005'; $basedate = strtotime('this friday', strtotime('31 August '.$season)); for($d=0;$d<=31;$d++) { $d2=strtotime("+".$d." day",$basedate); echo(date('m d Y',$d2)."\n"); } ----
3
2351
by: pchaitanya | last post by:
I have selected some list of valid dates to a label. now i need to find first day among the given dates from label contrl i got dates from calender control by clicking for entire week.. that is i have dates from sunday to saturday and I have to find which date is sunday......
8
2524
by: Innocent2104 | last post by:
Hi there, The script below displays the attached output but as shown, it skips certain days and i need to include these to calculate my avg balance for a certain month, i.e.Nov. How do i update the script to include for example between 01 Nov and 05 Nov, there was no entries, therefore my balance should remain the same & display my missing dates 02,03,04 Nov?? DECLARE @STARTDATE DATETIME, @ENDDATE DATETIME SET @STARTDATE = '2009-11-01' ...
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9399
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9957
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9835
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8832
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.