在Djang中获取当前日期(和时间)

2024-05-17 05:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道在django应用程序中获取当前日期的最佳方法是什么。

目前我查询PythonDateTime模块——但是由于我需要到处都是日期,我想Django可能已经有了一个用于此的内置函数。

例如,我想过滤在当前年份创建的对象,以便执行以下操作:

YEAR = datetime.date.now().year
currentData = Data.objects.filter(date__year=YEAR)

我应该在settings.py中定义YEAR变量,还是现在创建一个函数(),或者是否有用于此的内置函数?


Tags: 模块对象django方法函数应用程序datetimedate
2条回答

在模板中,已经有一个内置函数^{}

Displays the current date and/or time, using a format according to the given string. Such string can contain format specifiers characters as described in the date filter section.

Example:

It is {% now "jS F Y H:i" %}

在django1.8中,您可以将它与as一起使用:

{% now "Y" as current_year %}
{% blocktrans %}Copyright {{ current_year }}{% endblocktrans %}

在python代码中,日期没有django内置,只需使用pythondatetime.date.now()来创建自己的自定义函数。

是的,您可以用Pythonviews.py文件以任何格式获取当前日期。

在views.py中

import datetime

def your(request)
    now=datetime.datetime.now()
    print("Date: "+ now.strftime("%Y-%m-%d")) #this will print **2018-02-01** that is todays date

相关问题 更多 >