Reputation: 71
I'm writing small social web application using Django. So I need to count minutes from post publishing (e.g like it looks in Twitter)
I tried to do something like this:
class Post(models.Model):
# post model fields
date = models.DateTimeField('Date')
@property
def publish_date(self):
if self.date >= (timezone.now() - datetime.timedelta(hours=1)):
return f'{timezone.now().minute - self.date.minute} minutes ago'
else:
return self.date
And use it into HTML like this: <span id="post_date">{{ p.publish_date }}</span>
, where p
is post instance
But sometimes it's returns negative values (like in example below)
So how can I correctly realize this?
Upvotes: 0
Views: 58
Reputation: 1058
In your HTML, you can use the naturaltime
template filter.
<span id="post_date">{{ p.date | naturaltime}}</span>
or, also the timesince
,
<span id="post_date">{{ p.date | timesince }}</span>
Upvotes: 2