[Django]-Django – TimeField difference

2👍

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.
👤Shariq

2👍

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.

Leave a comment