Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count only weekdays from timedelta in python

I am getting the number of days until the next "billing cycle" (for example) which starts on the nth day of the month:

from dateutil.relativedelta import relativedelta

dt = datetime.utcnow() + relativedelta(months=1,day=schedule.cycle_start)
days_till_next_cycle = dt - datetime.utcnow()

Where schedule.cycle_start is going to be something like 2 for the second day of the month.

This works... But:

How do I find the number of weekdays in that timedelta.

I took a look at https://pypi.python.org/pypi/BusinessHours/ and could not find any documentation.

I also saw this: Business days in Python which linked me to the link above and rolling my own. It's also been 4 years since that post and I was hoping there might be a simpler way?

like image 261
Johnston Avatar asked Jan 16 '14 02:01

Johnston


2 Answers

With rrule I was able get the following using the dt definition from above:

    from dateutil.rrule import *
    number_weekdays = rrule(WEEKLY, byweekday=(MO,TU,WE,TH,FR), dtstart=datetime.utcnow(),until=dt).count()
like image 88
Rob Parker Avatar answered Sep 21 '22 19:09

Rob Parker


Here a simple function that compute the number of business days between 2 dates:

def business_days(since, until):
    since_isoweekday = since.isoweekday() + 1
    return len([x for x in range(since_isoweekday,
                                 since_isoweekday + (until - since).days)
                if x % 7 not in [0, 6]])

not in [0, 6] stands for saturday and sunday.

Some tests:

>>> since = datetime.datetime(2014, 6, 2)
>>> until = datetime.datetime(2014, 6, 30)
>>> business_days(since, until)
20
>>> since = datetime.datetime(2014, 6, 25)
>>> until = datetime.datetime(2014, 7, 4)
>>> business_days(since, until)
7
like image 44
Stan Avatar answered Sep 21 '22 19:09

Stan