Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - TimeField difference

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?

like image 507
WitnessTruth Avatar asked Aug 31 '26 18:08

WitnessTruth


1 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.
like image 185
Shariq Avatar answered Sep 03 '26 11:09

Shariq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!