0

I'm working with Django and I fall into a problem that blocked me. I write this method to perform a duration as a difference between "end_time" and "start_time", the result is a timedelta object.

@property
def start_dt(self):
    if self.track and self.track.dt > 0 and not self.sample_intervals.is_empty():
        try:
            return self.track.timestamp + datetime.timedelta(seconds=self.track.dt * self.sample_intervals.min())
        except BaseException:
            return None
    else:
        intervals = self.get_datetime_intervals()
        return intervals.min()

@property
def end_dt(self):
    if self.track and self.track.dt > 0 and not self.sample_intervals.is_empty():
        try:
            return self.track.timestamp + datetime.timedelta(seconds=self.track.dt * self.sample_intervals.max())
        except BaseException:
            return None
    else:
        intervals = self.get_datetime_intervals()
        return intervals.max()

@property
def duration(self):
    return self.end_dt - self.start_dt

It works well, but if I have, for example, 00:32:55.765000, the result is approximated down and I obtain 00:32:55 instead of 00:32:56.

How can I approximate up or down depending on duration's microseconds?

  • 1
    I read that chopping looks to be less confusing to most people than rounding. See this [stackoverflow](https://stackoverflow.com/questions/11040177/datetime-round-trim-number-of-digits-in-microseconds) – Hommes Dec 28 '21 at 08:26
  • 2
    To be clear, the problem is only with how the `timedelta` is *displayed* (or converted to a string representation)? Or is the actual time value incorrect? – Karl Knechtel Dec 28 '21 at 08:44
  • Thanks a lot guys! Anyway, to answer to the last question, I need both. This https://stackoverflow.com/questions/11040177/datetime-round-trim-number-of-digits-in-microseconds helps me to get the correct value in the backend – CanAnyOneHelpMe Dec 28 '21 at 11:03

0 Answers0