0

I want to know about the best way to find the difference between two time objects in Django. I want to know whether the time of a particular object is in a difference of 4 hours or not.

I have my models.py as

class Task(models.Model):
    time = models.TimeField()

In the shell, I tried something like

from django.utils.timzone import datetime, timedelta
obj_time = Task.objects.first().time
obj_time - datetime.now().time() < timedelta(hours=4) 

But I get the following error

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

How should I go about solving this?

Shahrukh Mohammad
  • 985
  • 2
  • 17
  • 33
  • Can't you use the actual `datetime` objects, instead of the `time` ones? The latter run into problems when their difference passes midnight: should it become negative (not a time), or a value module 24 hours (which is a time, not but the time interval you're looking for). 11 hours - 12 hours = -1 hour or 23 hours? Hence, `datetime`s do support subtraction (differencing). –  Dec 19 '17 at 02:56
  • Possible duplicate of [subtract two times in python](https://stackoverflow.com/questions/5259882/subtract-two-times-in-python) – Galen Dec 19 '17 at 02:57
  • if I store my time as a datetime field, than how will I use something like `timezone.now() - self.time` to get the time difference only as `timezone.now()` will include the date as well, and `self.time` also has a date, therefore I won't be able to get just the time difference which I need – Shahrukh Mohammad Dec 19 '17 at 04:09
  • Ok I solved my problem by using the seconds of a timedelta object to get just the time difference I needed and than comparing the seconds of a timedelta object like timedelta(hours=4) – Shahrukh Mohammad Dec 20 '17 at 05:26

0 Answers0