在 Django 中将日期时间格式转换为'a time ago'



我想将日期时间格式更改为"a time ago"。我知道有几种方法可以做到这一点。

我的第一个问题是什么是最好的方法?(使用html模板中的脚本,在views.py等中执行(

我在views.py中编写代码,但日期时间没有显示在模板中。

这是转换日期时间的代码:

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>

然后,如果我想把它写在剧本里,我该怎么做?

我将快速向您解释如何实现它,首先您必须在应用程序中安装该包,为此您必须将其添加到INSTALLED_APPS中,留下如下内容:

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

现在,在您的模板中,您表示将通过在开头添加以下内容来使用该应用程序:{% load humanize %}

现在,当您显示日期时,将在变量后面放置一个管道,并指示此链接的一个选项https://docs.djangoproject.com/en/3.1/ref/contrib/humanize/,看起来像这样:{{ notification.date|naturaltime }}}

在模板的末尾,它应该看起来像:

% extends 'base.html' %}
{% load humanize %}
{% block content %}
<ul>
{% for notification in notifications %}
<li>
{{ notification }}
<small>{{ notification.date|naturaltime }}</small>
</li>
{% endfor %}
</ul>
{% endblock %}

最新更新