h4cktivist
h4cktivist

Reputation: 71

Method that count minutes from post publishing

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)

enter image description here

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)

enter image description here

So how can I correctly realize this?

Upvotes: 0

Views: 58

Answers (1)

eshaan7
eshaan7

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

Related Questions