django - python - Skip weekend and public holiday when calculating duration between 2 datefield -
greeting everyone,
i have 2 datefield
in form, start_date
, end_date
, floatfield
called duration
. figure out how automatically save duration without user input calculating duration of start , end date, how can give condition skip weekend, , particular public holiday?
any appreciated
below code :
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): """ 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)
a possible solution can use numpy
's busday_count
function:
import numpy np def my_leaves_view(request): ... inst.duration = np.busday_count(inst.start_date, inst.end_date) ...
which gives days count without weekends , holidays.
Comments
Post a Comment