Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current date (and time) in Django

I was wondering what is the best way to get the current date in a django application.

Currently I query the python datetime module - but since I need the date all over the place I thought maybe Django already has a buildin function for that.

e.g. I want to filter objects created in the current year so I would do the following:

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

Should I define the YEAR variable in settings.py or create a function now() or is there a buildin Function for this?

like image 771
Maximilian Kindshofer Avatar asked Sep 08 '25 02:09

Maximilian Kindshofer


2 Answers

I think the fastest and cleanest way is to use the localdate function:

from django.utils.timezone import localdate
today = localdate()

Or, there is also localtime, which is the current datetime in the project's timezone:

from django.utils.timezone import localtime
today = localtime().date()

However, remember that now().date() may be different from current date, since it uses UTC:

Note that now() will always return times in UTC regardless of the value of TIME_ZONE; you can use localtime() to get the time in the current time zone.

like image 148
arcstur Avatar answered Sep 09 '25 16:09

arcstur


In templates, there is already a built-in function 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" %}

In django 1.8, you can use it with as:

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

In python code, there is no django builtin for date, just use the python datetime.date.now() to make your own customized function.

like image 35
Assem Avatar answered Sep 09 '25 15:09

Assem