Django: How to get a time difference from the time post?


Question

Say I have a class in model

 class Post(models.Model):
     time_posted = models.DateTimeField(auto_now_add=True, blank=True)

     def get_time_diff(self):
         timediff = timediff = datetime.datetime.now() - self.time_posted
         print timediff # this line is never executed
         return timediff

I defined a get_time_diff to get the time difference from the time when the Post is posted up to now, according to the document, the DateTimeField should be able to be converted to datetime automatically, is that correct? Why the print statement is never being run? How can you extract the time difference?

Beside, if you get a time difference, is there an easy way to convert the time difference to an integer, like the number of seconds of the total time.

1
19
3/9/2016 8:00:47 PM

Accepted Answer

Your code is already working; a datetime.timedelta object is returned.

To get the total number of seconds instead, you need to call the .total_seconds() method on the resulting timedelta:

from django.utils.timezone import utc

def get_time_diff(self):
    if self.time_posted:
        now = datetime.datetime.utcnow().replace(tzinfo=utc)
        timediff = now - self.time_posted
        return timediff.total_seconds()

.total_seconds() returns a float value, including microseconds.

Note that you need to use a timezone aware datetime object, since the Django DateTimeField handles timezone aware datetime objects as well. See Django Timezones documentation.

Demonstration of .total_seconds() (with naive datetime objects, but the principles are the same):

>>> import datetime
>>> time_posted = datetime.datetime(2013, 3, 31, 12, 55, 10)
>>> timediff = datetime.datetime.now() - time_posted
>>> timediff.total_seconds()
1304529.299168

Because both objects are timezone aware (have a .tzinfo attribute that is not None), calculations between them take care of timezones and subtracting one from the other will do the right thing when it comes to taking into account the timezones of either object.

31
9/28/2018 9:22:14 AM

Assuming you are doing this within a template, you can also use the timesince template tag.

For example:

{{ blog_date|timesince:comment_date }}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon