Python3: How to calculate the number of working days between two dates?

1

Friends,

I would like to know how to calculate the number of working days between two dates in Python 3.

Thank you!

[]'s

    
asked by anonymous 18.01.2018 / 19:36

2 answers

2

Then, as in Diego's answer, knowing the number of days between two dates, just subtract two objects of type date and get the days attribute. Now on working days: - counting on Saturdays and Sundays is quiet - the date has how to check the .weekday , and then you can do more or less accounts, at the risk of an error, or make a loop and count the days.

Looping from one date to the next is an excellent opportunity to create a Python iterator: a function definition with the yield keyword that can then be used directly in a for:

def iterdates(date1, date2):
    one_day = datetime.timedelta(days = 1)
    current = date1
    while current < date2:
        yield current
        current += one_day

And then you can do it:

a = datetime.date(2018,1, 25)
b = datetime.date(2018, 2, 10)

for d in iterdates(a, b):
    if d.weekday() not in (5, 6):
        print (d, d.weekday())

Or, to count the days:

dias_de_semana = sum(1 for day in iterdates(a, b) if day.weekday not in (5,6))

(weekday 5 and 6 are Saturday and Sunday)

Holidays, of course it's tricky: either you find an API that answers any holiday in the desired country in the world (there may be something like this on google calendar), or hard coding national holidays, and compares the same.

For example, you can make a dictionary:

feriados = {
    "confraternização universal": date(2018, 1, 1),
    "carnaval": date(2018, 2, 13),
    ...
}

and then use something similar to the previous expression:

dias_uteis = sum(1 for day in iterdates(a, b) if day.weekday not in (5,6) and day not in feriados.values())
    
20.01.2018 / 03:32
0

You can use this library.

from datetime import date
from = date(2008, 8, 18)
to   = date(2008, 9, 26)
delta = from - to
print delta.days
    
18.01.2018 / 19:47