简体   繁体   English

如何检查日期是否在未来?

[英]How to check whether the date is in the future?

I need to display the information if the date given is in the future.如果给定的日期是将来的日期,我需要显示信息。 Is there a way to do this in a template?有没有办法在模板中执行此操作?

I found out I should compare them as timestamps but the following code gives me "jinja2.exceptions.UndefinedError: 'as_timestamp' is undefined".我发现我应该将它们作为时间戳进行比较,但下面的代码给了我“jinja2.exceptions.UndefinedError:‘as_timestamp’未定义”。

{% if as_timestamp(bibjson.discontinued_date) <=  as_timestamp(time.today) %}
  <p>This date should be displayed only if in the past: {{ date.strftime("%d %B %Y") }}</p>
{% endif %}

It is very easy with custom filter https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/使用自定义过滤器非常容易https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/

The filter file:过滤器文件:

import datetime

from django.template import Library

register = Library()


@register.filter('date_in_the_past')
def date_in_the_past(date):
    now = datetime.datetime.now()
    return date <= now

and in the template:在模板中:

{% load filter %}
{% if bibjson.discontinued_date|date_in_the_past %}
    <p>This date should be displayed only if in the past: {{ bibjson.discontinued_date|date:'d F Y' }}</p>
{% endif %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Jinja 2模板:我如何在if语句中检查布尔值是否为False或None - Jinja 2 Templates: how I check in an if statement whether the boolean is False or None 如何检查变量是否已定义,当 ansible/j2 中可能缺少字典时 - How to check whether variable is defined, when dictionary may be missing in ansible/j2 如何使用flask检查每个文件夹是否都有特定文件,并使用jinja2显示结果? - How to use flask to check whether every folder has specific files or not and using jinja2 to show the result? Django Jinja 如何通过模板查看用户是否有权限? - Django Jinja How to check whether the user has any rights through the template? 在Jinja2中检查日期时间对象是否与今天一致 - Check whether datetime object agrees with today in jinja2 使用数据构建工具(dbt)和雪花,如何检查列是否为日期字段? - Using data build tool(dbt) and snowflake, how can I check if a column is a date field? 如何确定一个值是否为空? - How can I determine whether a value is empty? 我想检查类别页面中的产品是否存在于购物车中,然后使用 django 和 jinja 在网页中显示添加的图标 - I want to check whether the products in the category page exists in cart then show a added icon in webpage using django and jinja 如何检查变量是否是神社中的字典 - How to check if a variable is a dictionary in jinja 如何使用jinja2插入当前日期 - How to insert the current date with jinja2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM