3

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?

WitnessTruth
  • 539
  • 2
  • 9
  • 27
  • 1
    What do you expect the output to be here? You need to use `datetime` to compare two moments in time. Python's `time` does not support `-` operation. What's the distance from "noon" to "noon"? Zero? 24 hours? The operation does not make sense unless you also have date context with the time. – Håken Lid Dec 17 '18 at 12:37
  • Possible duplicate of [How do you get the difference between two time objects in Python](https://stackoverflow.com/questions/25265379/how-do-you-get-the-difference-between-two-time-objects-in-python) – Håken Lid Dec 17 '18 at 12:41
  • try to use `models.DateTimeField` instead – Chiefir Dec 17 '18 at 12:41

2 Answers2

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
  • 513
  • 4
  • 14
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.

ariannedee
  • 41
  • 4
  • The problem is, for most cases you can't assume the times are "in the same day". You might have a timerange from 23:00 to 02:00 for example that you want to compare with some specific time-of-day. – BjornW Jan 30 '20 at 14:25
  • If that's a case you need to support, then if end_time is less than start time, add 24*60 to it to make it a day ahead. If there are more cases you need to support, then date times are obviously required. – ariannedee Jan 31 '20 at 16:58