Home > Mobile >  Calculate the number of deltas between two dates
Calculate the number of deltas between two dates

Time:05-05

I want to calculate how many relativedelta() there are between two date objects. My code is below, it's not working though as a relative delata cannot divide a date, but maybe it shows what I'm trying to do.

For example, if my relative delta is one week relativedelta(weeks=1) and my dates are 2022-05-01 and 2022-05-15 then two of the 1 week deltas will fit into the two dates that are two weeks apart.

        delta=relativedelta(days= self.cleaned_data['delta_days'], months=self.cleaned_data['delta_months'])
        no_loops = (self.cleaned_data['to_date'] - self.cleaned_data['from_date']) / delta
        if no_loops > 36: raise ValidationError('Too many iterations.')

CodePudding user response:

Let me know if this helps

    #calculate delta between two dates
    def delta_days(start_date, end_date):
        start = datetime.strptime(start_date, "%m/%d/%Y")
        end = datetime.strptime(end_date, "%m/%d/%Y")
        delta = end - start
        return delta.days

CodePudding user response:

I've used this solution for now. It doesn't feel very clean but it works.

        start_date = self.cleaned_data['from_date']
        iterations = 0
        while start_date < self.cleaned_data['to_date']:
            iterations  = 1
            start_date  = relativedelta(days=self.cleaned_data['delta_days'], weeks=self.cleaned_data['delta_weeks'], months=self.cleaned_data['delta_months'])
        if iterations > 36: raise ValidationError('The selected date range and deltas result in too many dates to calculate. Please reduce scope to 36 or less dates.')

CodePudding user response:

try this one. First you have to convert date difference and relative delta to days (integer) to perform the arithmetic you needed

delta=relativedelta(days= self.cleaned_data['delta_days'], months=self.cleaned_data['delta_months'])
no_loops = (self.cleaned_data['to_date'] - self.cleaned_data['from_date']).days / delta.days
if no_loops > 36: raise ValidationError('Too many iterations.')
  • Related