Python 如何比较 Django 模板中的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3798812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare dates in Django templates
提问by Herman Schaaf
I would like to compare a date to the current date in Django, preferably in the template, but it is also possible to do before rendering the template. If the date has already passed, I want to say "In the past" while if it is in the future, I want to give the date.
我想将日期与 Django 中的当前日期进行比较,最好是在模板中,但也可以在渲染模板之前进行。如果日期已经过去,我想说“过去”,如果是未来,我想给出日期。
I was hoping one could do something like this:
我希望有人可以做这样的事情:
{% if listing.date <= now %}
In the past
{% else %}
{{ listing.date|date:"d M Y" }}
{% endif %}
With now being today's date, but this does not work. I couldn't find anything about this in the Django docs. Can anyone give some advice?
现在是今天的日期,但这不起作用。我在 Django 文档中找不到任何关于此的信息。任何人都可以提供一些建议吗?
采纳答案by bx2
Compare date in the view, and pass something like in_the_past(boolean) to the extra_context.
比较视图中的日期,并将类似in_the_past(boolean) 的内容传递给 extra_context。
Or better add it to the model as a property.
或者更好地将其作为属性添加到模型中。
from datetime import date
@property
def is_past_due(self):
return date.today() > self.date
Then in the template:
然后在模板中:
{% if listing.is_past_due %}
In the past
{% else %}
{{ listing.date|date:"d M Y" }}
{% endif %}
Basically the template is not the place for date comparison IMO.
基本上模板不是IMO日期比较的地方。
回答by monokrome
You can always pass datetime.datetime.now (since django models use Python's standard datetime object).
您始终可以传递 datetime.datetime.now (因为 django 模型使用 Python 的标准日期时间对象)。
Using render_to_response, you could do something like this (after importing datetime):
使用render_to_response,你可以做这样的事情(导入日期时间后):
return render_to_response('template.html', {'now': datetime.datetime.now()})
Now that you have access to "now" inside of the template, you can compare dates just like you did in your examples.
现在您可以访问模板中的“现在”,您可以像在示例中一样比较日期。
Furthermore, if you use RequestContext in your views - you will be able to add "now" as a context_processor if you need this in multiple files. This will add "now" to any template rendered with a RequestContext.
此外,如果您在视图中使用 RequestContext - 如果您在多个文件中需要它,您将能够添加“now”作为 context_processor。这会将“现在”添加到使用 RequestContext 呈现的任何模板。
However, it is more realistic that you simply just get the list of records that are before now in your original queryset and avoid querying for useless data in the first place:
但是,更现实的是,您只需获取原始查询集中之前的记录列表,并避免首先查询无用数据:
listing.objects.filter(date__lt=datetime.datetime.now())
回答by adiktofsugar
I added date_now to my list of context processors.
我将 date_now 添加到我的上下文处理器列表中。
So in the template there's a variable called "date_now" which is just datetime.datetime.now()
所以在模板中有一个名为“date_now”的变量,它就是 datetime.datetime.now()
Make a context processor called date_now in the file context_processors.py
在文件 context_processors.py 中创建一个名为 date_now 的上下文处理器
import datetime
def date_now(request):
return {'date_now':datetime.datetime.now()}
And in settings.py, modify CONTEXT_PROCESSORS to include it, in my case it's
在 settings.py 中,修改 CONTEXT_PROCESSORS 以包含它,在我的情况下是
app_name.context_processors.date_now
回答by Evren Kutar
addition to @bx2 beneficial answer, if your field is a datetime field just call date() function to models datetimefield:
除了@bx2 有益的答案,如果您的字段是日期时间字段,只需调用 date() 函数来模拟日期时间字段:
from datetime import date
@property
def is_past_due(self):
if date.today() > self.date.date():
return True
return False
回答by Dustin O
I found this question and had a similar problem. I was looking to display information if it had only occurred in the past.
我发现了这个问题并遇到了类似的问题。我希望显示过去只发生过的信息。
Using Django's "timesince" tag in the template I was able to solve my problem. I'm not saying it's efficient, but it works for me.
在模板中使用 Django 的“timesince”标签,我能够解决我的问题。我并不是说它有效,但它对我有用。
In Template:
在模板中:
{% if model_name.date_time|timesince >= "1 min" %}
<p>In the past</p>
{% else %}
<p>{{ model_name.date_time }}</p>
{% endif %}
回答by Dirk Bergstrom
As of Django 1.8 the following slightly distasteful construct does the job:
从 Django 1.8 开始,以下有点令人反感的构造完成了这项工作:
{% now "Y-m-d" as todays_date %}
{% if todays_date < someday|date:"Y-m-d" %}
<h1>It's not too late!</h1>
{% endif %}
Hackish, but it avoids the need for a custom tag or context processor.
Hackish,但它避免了对自定义标签或上下文处理器的需要。
回答by Sherd
I believe the easiest way to achieve this is by importing datetime in your views.py and passing today's date as context data.
我相信实现这一目标的最简单方法是在您的 views.py 中导入日期时间并将今天的日期作为上下文数据传递。
context['today'] = datetime.date.today()
Then in the template tags you could do something like this.
然后在模板标签中你可以做这样的事情。
{% if listing.date < today % }
This way if you are passing a list of objects as context, you can apply the filter to each line as you output it in the HTML template. I had a list of items that I had filtered out and was using Bootstrap to stylize as I displayed them. I wanted to make overdue dates stand out and applied the filtering only if one of my dates was less than today's date.
这样,如果您将对象列表作为上下文传递,则可以在 HTML 模板中输出时将过滤器应用于每一行。我有一个已过滤掉的项目列表,并在显示它们时使用 Bootstrap 进行样式化。我想让过期日期脱颖而出并仅在我的日期之一小于今天的日期时才应用过滤。

