Comparing timestamps

21 views
Skip to first unread message

K.Berkhout

unread,
May 30, 2009, 2:31:01 PM5/30/09
to Django users
Hi,

Let's say I have the following post model:

class Post(models.Model):
text = models.TextField()
created = models.DateTimeField(auto_now=False, auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True,
auto_now_add=False)

I want to display the last_modified date in my template, but only if
it's different from the creation date.
(in other words: don't let the template display the last_modified
date, if the post hasn't been modified yet)
The following code in the template should work:

{% ifnotequal post.created post.last_modified %}
Last modified at {{ post.last_modified|date:"l d M Y" }}
{{ post.last_modified|date:"H.G" }}u
{% endifnotequal %}

But it doesn't, because Django saves the timestamps with microsecond
precision, e.g. for a newly created post:
Created: 2009-05-30 19:09:25.790253
Last_modified: 2009-05-30 19:09:25.790280

I've tried doing something like:
{% ifnotequal topic.created|date:"l d M Y" topic.last_updated|date:"l
d M Y" %}

But of course, that won't work.
Is there any way I could compare two timestamps, without that high
level of precision?

Thanks,

Kevin

Damien GOMBAULT

unread,
May 30, 2009, 4:11:41 PM5/30/09
to Django users
Write a method is_modified in your Post model.
You can use datetime.timedelta to compare dates.

def is_modified(self):
second = datetime.timedelta(seconds=1)
delta = self.last_modified - self.created
return delta >= second

Then use it in your template :

{% if post.is_modified %}
{{ ... }}
{% endif %}

K.Berkhout

unread,
May 31, 2009, 6:29:47 AM5/31/09
to Django users
Thanks you very much for the solution, Damien!

K.Berkhout

unread,
May 31, 2009, 8:29:51 AM5/31/09
to Django users
Hmm, seems like the method always returns false, anybody knows what
goes wrong?

K.Berkhout

unread,
May 31, 2009, 8:36:07 AM5/31/09
to Django users
Already got it, it's:
timedelta(seconds=1)

In stead of:

datetime.timedelta(seconds=1)
Reply all
Reply to author
Forward
0 new messages