Python Django:计算工作日 [英] Python Django: Count business days
本文介绍了Python Django:计算工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要计算两个日期之间的工作日。此外,我还必须删除单独的表格(节假日)中列出的日期。
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
推荐答案
为您提供一个非常简单的技巧,使用numpy,更准确地说:
Just a very quick tip for you, use numpy, and to be more exact:
https://docs.scipy.org/doc/numpy/reference/generation/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)
之后,您可以像这样:
count = np.busday_count(begindate, enddate, weekmask='1111100', busdaycal=bd_cal)
这篇关于Python Django:计算工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文