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

Getting the current date (and time) in Django

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

目前我查询 python 日期时间模块 - 但由于我到处都需要日期,我想也许 Django 已经有一个内置函数。

例如我想过滤当年创建的对象,所以我会执行以下操作:

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

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

在模板中,已经有一个内置函数now:

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" %}

在 django 1.8 中,你可以使用它 as:

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

在python代码中,django没有内置date函数,只需要使用python datetime.date.now()自定义函数即可。

是的,您可以在 Python views.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