Question

I have a model with two TimeFields. I want to show the time difference in a template (ie, 27 minutes). I see the filter timesince, but it isn't working; I think it only accepts datetimes but my models have stored times only.

Response to @HAL:

'datetime.time' object has no attribute 'year'
Exception Location: C:\Python27\lib\site-packages\django\utils\timesince.py in timesince, line 32
Was it helpful?

Solution 2

You can only compare two time stamps if you know their corresponding dates and timezones.. The datetime.time class contains only the time. I strongly advise you to consider using a DateTimeField (which uses datetime.datetime) in this case.

If you are sure that both datetime.time objects are having the same date and timezone, then you can add method to your model like this:

import datetime
from django.utils.timesince import timesince

class MyModel(models.Model):
...

    def get_time_diff(self):
        dummydate = datetime.date(2000,1,1)  # Needed to convert time to a datetime object
        dt1 = datetime.combine(dummydate,self.t1)
        dt2 = datetime.combine(dummydate,self.t2)
        return timesince(dt1, dt2)   # Assuming dt2 is the more recent time

Here the time values are upgraded to a datetime value using an arbitrary date. You can invoke this from the template as {{ obj.get_time_diff }}.

OTHER TIPS

You can use timesince template tag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top