Compute working days

G

Gonsolo

I found no solution on the net so I am posting my solution here.
It can be called with "python cwd 1-1-2009 14-3-2009"

from dateutil.rrule import *
from dateutil.parser import *
from datetime import *
from sys import *

start = parse( argv[1] )
#end = datetime.now()
end = parse( argv[2] )
workdays = ( MO, TU, WE, TH, FR )

r = rrule(DAILY, byweekday=workdays, dtstart = start, until = end)
print len( list( r ) )


g
 
J

John Machin

I found no solution on the net so I am posting my solution here.
It can be called with "python cwd 1-1-2009 14-3-2009"

from dateutil.rrule import *
from dateutil.parser import *
from datetime import *
from sys import *

Hmmmm ... I wonder what the style police will have to say about that
little lot :)
start = parse( argv[1] )
#end = datetime.now()
end = parse( argv[2] )
workdays = ( MO, TU, WE, TH, FR )

r = rrule(DAILY, byweekday=workdays, dtstart = start, until = end)
print len( list( r ) )

# Look, Ma, no 3rd party modules!
import datetime
for start in range(1, 8):
print
d1 = datetime.date(2009, 3, start)
day1 = d1.toordinal()
dow1 = (day1 - 1) % 7
for delta in range(8):
d2 = datetime.date(2009, 3, start + delta)
day2 = d2.toordinal()
dow2 = (day2 - 1) % 7
workdays = (day2 + 7 - dow2 - day1 + dow1) // 7 * 5 - min
(dow1, 5) - max(4 - dow2, 0)
print d1, d2, dow1, dow2, workdays
# Assumes both endpoints are included e.g. Mon 2 March to Tue 3 March
is 2 work-days.

HTH,
John
 
C

Casey Webster

How about:

from datetime import date, timedelta

# Define the weekday mnemonics to match the date.weekday function
(MON, TUE, WED, THU, FRI, SAT, SUN) = range(7)

def workdays(start_date, end_date, whichdays=(MON,TUE,WED,THU,FRI)):
'''
Calculate the number of working days between two dates inclusive
(start_date <= end_date).

The actual working days can be set with the optional whichdays
parameter
(default is MON-FRI)
'''
delta_days = (end_date - start_date).days + 1
full_weeks, extra_days = divmod(delta_days, 7)
# num_workdays = how many days/week you work * total # of weeks
num_workdays = (full_weeks + 1) * len(whichdays)
# subtract out any working days that fall in the 'shortened week'
for d in range(1, 8 - extra_days):
if (end_date + timedelta(d)).weekday() in whichdays:
num_workdays -= 1
return num_workdays
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,511
Members
48,206
Latest member
EpifaniaMc

Latest Threads

Top