omid jahadi
omid jahadi

Reputation: 161

convert datetime format to 'a time ago' in django

I want to change datetime format to 'a time ago'. I know there are several ways to do that.

My first question is what is the best way? (using script in html template, do that in views.py or etc)

I write the code in views.py, but datetime doesn't show in template.

This is the code for convert datetime:

date = float(models.Catalogue.objects.get())
d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f')
now = datetime.datetime.now()
time_ago = timeago.format(d_datetime, now, 'fa_IR')

views.py:

class crawler(generic.ListView):
    paginate_by = 12
    model = models.Catalogue
    template_name = 'index.html'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        for cat in models.Catalogue.objects.all():
            if models.Catalogue.source == 'kilid':
                date = float(models.Catalogue.objects.get())
                d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
                d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f')
                now = datetime.datetime.now()
                time_ago = timeago.format(d_datetime, now, 'fa_IR')
                context['time_ago'] = time_ago
        return context

index.html:

<div class="card-footer" dir="rtl" style="text-align:right">
     <small id="datetime">{{ time_ago }}</small>
</div>

And then, if I want to write it in a script, how can I do that?

Upvotes: 0

Views: 1264

Answers (1)

Sergio Ribera
Sergio Ribera

Reputation: 196

I explain you quickly how to implement it, first you must install that package in your apps, for that you must add it to your INSTALLED_APPS, leaving you something like this:

INSTALLED_APPS = [
    # ....
    'django.contrib.humanize',
]

Now in your templates you indicate that you will make use of that APP by adding this at the beginning: {% load humanize %}

Now when you display a date you do it placing a pipe after the variable and indicating one of the options of this link https://docs.djangoproject.com/en/3.1/ref/contrib/humanize/, looking something like this: {{ notification.date|naturaltime }}}

At the end of your template it should look like:

% extends 'base.html' %}

{% load humanize %}

{% block content %}
  <ul>
    {% for notification in notifications %}
      <li>
        {{ notification }}
        <small>{{ notification.date|naturaltime }}</small>
      </li>
    {% endfor %}
  </ul>
{% endblock %}

Upvotes: 4

Related Questions