在计算2个日期字段之间的持续时间时,请跳过周末和公众假期

时间:2017-08-18 07:16:50

标签: python django datefield

我的表单中有2 DateFieldstart_dateend_date以及FloatField,名为duration。我想通过计算开始和结束日期的持续时间来弄清楚如何在没有用户输入的情况下自动保存持续时间,但是我如何给出跳过周末和任何特定公共假期的条件?

model.py:

class Leave(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+')
    start_date = models.DateField()
    end_date = models.DateField()
    duration = models.FloatField(null=True, blank=True)

form.py:

class LeavesDetailForm(forms.ModelForm):
    class Meta:
        model = Leave
        fields = ('employee', 'start_date', 'end_date', 'duration')
        widgets = {'start_date': forms.DateInput(attrs={'type': 'date'}),
                   'end_date': forms.DateInput(attrs={'type': 'date'}),
                   'employee': forms.HiddenInput(),
                   'duration': forms.HiddenInput()}

view.py:

def my_leaves_view(request):
    """
   My Leaves view
    :param request:
    :return:
    """
    form = LeavesDetailForm(request.POST or None)
        if form.is_valid():
            inst = form.save(commit=False)
            inst.start_date = form.cleaned_data['start_date']
            inst.end_date = form.cleaned_data['end_date']
            duration = (inst.end_date - inst.start_date).days
            inst.duration = duration
            inst.save()
            return HttpResponseRedirect('/hrm/employee/leaves')
    return render(request, 'hrm/employee/details/my_leaves.html', context)

1 个答案:

答案 0 :(得分:2)

可能的解决方案是使用numpy' busday_count功能:

import numpy as np


def my_leaves_view(request):
    ...
    inst.duration = np.busday_count(inst.start_date, inst.end_date)
    ...

在没有周末和假期的情况下确切地给出了天数。