Django: How to get a time difference from the time post?
Assuming you are doing this within a template, you can also use the timesince template tag.
For example:
{{ blog_date|timesince:comment_date }}
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.