Compute working days

MRAB python at mrabarnett.plus.com
Wed Aug 18 18:33:02 EDT 2021


On 2021-08-18 20:57, Bruno Lirio wrote:
> Em sábado, 14 de março de 2009 às 13:59:41 UTC-3, Casey escreveu:
>> 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
> Could it include the holidays in Brazil?
> 
Yes. The algorithms calculates the number of working days, assuming no 
holidays, so you'd then subtract any working days between the start and 
end dates that are actually holidays.


More information about the Python-list mailing list