Python Django: Count business days

给你一囗甜甜゛ 提交于 2020-08-26 09:48:05

问题


I need to count business days between two dates. In addition, I must also remove the days listed in a separate table (holidays).

So far I have this code. It counts the days but does not remove the days from the separate table (holidays).

class Holidays(models.Model):
    class Meta:
        ordering = ['date']

    date = models.DateField(null=True, verbose_name='Date')

class Situation(models.Model):
    class Meta:
        ordering = ['date_time_start']

    date_time_start = models.DateTimeField(null=True, blank=False, verbose_name='Date/Time Start')
    date_time_end = models.DateTimeField(null=True, blank=False, verbose_name='Date/Time End')

    @property
    def business_days(self):
        holidays = Holidays.objects.values_list('date', flat=True)
        oneday = datetime.timedelta(days=1)
        dt = self.date_time_start.date()
        total_days = 0
        while (dt <= self.date_time_end.date()):
            if not dt.isoweekday() in (6, 7) and dt not in holidays.values():
                total_days += 1
            dt += oneday
        return total_days

回答1:


Just a very quick tip for you, use numpy, and to be more exact:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.busday_count.html

it has everything that you need: It counts business days between two dates and you can create a list of your own holidays, like so:

bd_holidays = ['2019-12-25', '2019-12-26']
bd_cal = np.busdaycalendar(holidays=bd_holidays)

after this you can go like:

count = np.busday_count(begindate, enddate, weekmask='1111100', busdaycal=bd_cal)


来源:https://stackoverflow.com/questions/58502797/python-django-count-business-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!