Getting the current date (and time) in Django

15,549

Solution 1

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.

Solution 2

Yes you can get the the current date in Python views.py file in any format you want.

In 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
Share:
15,549

Related videos on Youtube

Maximilian Kindshofer
Author by

Maximilian Kindshofer

Mostly Django

Updated on June 04, 2022

Comments

  • Maximilian Kindshofer
    Maximilian Kindshofer almost 2 years

    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?

  • Maximilian Kindshofer
    Maximilian Kindshofer over 8 years
    Yes for the templates there is, but Iam searching for an equivalent in views.py
  • Assem
    Assem over 8 years
    in views.py you have datetime.date.now().year, it does her job well
  • Maximilian Kindshofer
    Maximilian Kindshofer over 8 years
    It returns the current year and it works well, I just wondered instead of using datetime using a django "buildin" function or writing an own function - so I can use it like a function
  • Assem
    Assem over 8 years
    There is no django builtin function for date to use in python code, I think you should do your own function based on datetime.date.now().year. I updated my answer
  • Ralf
    Ralf almost 5 years
    Just to add more info to an already great answer: If you ever need the current date/time in a template as a variable (date or datetime instead of str as shown in this answer) you can find a few options in this answer I wrote some time ago.
  • Love Putin
    Love Putin almost 4 years
    @Ralf - Great answer. Takes care of many situations. And answers Max's answer in a proper and correct manner.