Ad

Django: How To Return The Hours Difference Between Current Time And The Value Of DateTimeField?

I try to get time difference between now and a data's last call and monitoring that in the website.

my models.py codes are;

class MyModel(models.Model):
    th_id = models.CharField(max_length=55)
    src_id = models.IntegerField()
    call_time = models.DateTimeField()

    @property
    def time_diff(self):
        if self.call_time:
            return (datetime.now().date() - self.call_time.date()) > timedelta(hours=2)
        else:
            return 0
    def now_diff(self):
        return datetime.now().date() - self.call_time.date()

But I need the now_diff function to return the hours difference also. I have searched the internet but can't find any solution, date() object doesn't return hours or minutes. Is there a way?

Ad

Answer

To compute the hours diff. you can write your function as follow:

def now_diff(self):
    delta = datetime.now() - self.call_time
    return delta.total_seconds() / (60 * 60)

Note: The difference between two dates or times returns timedelta object.

Ad
source: stackoverflow.com
Ad