Django - TimeField difference

Viewed 3271

I would like to compare two time fields to get the difference in hours and minutes.

class Labor(models.Model):
    id = models.AutoField(primary_key=True)
    start_hour = models.TimeField(null=True)
    end_hour = models.TimeField(null=True)

    def hours(self):
        return self.end_hour - self.start_hour 

But, if try to use the hours method, django throws this exception:

unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

I would like that the difference returns me something like this:

10:00 ~ 11:30 = 1:30

11:30 ~ 11:45 = 0:15

How could I do that?

2 Answers

First make the fields as DateTimeField as @Chiefir mentioned, this gives you a datetime object.

then,

def hours(self):
        c = self.end_time - self.start_time
        print(c.seconds) 
        # Write your logic to convert seconds to hours.

If you don't want to make your fields DateTimeFields, you can just do some quick math (assuming your times are in the same day).

def hours(self):
    end_minutes = self.end_hour.hour*60 + self.end_hour.minute
    start_minutes = self. start_hour.hour*60 + self.start_hour.minute
    return (end_minutes - start_minutes) / 60

That will return a float, but you can always round the value. You may also want to check to make sure self.end_hour is greater than self.start_hour.

Related