问题
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