Skip to content
Advertisement

How to display current date and time on Django website?

I know how to print out current date and time in the console, but I am trying to add the date/time as a feature on my daily task Python website using Django and Bootstrap4.

I have tried adding it as a function in my views.py file and then inserting the function in the html file of the page i want it to be on, but everything I have tried has not worked.

Here is the function I created at first in views.py:

def today():
    """Shows todays current time and date."""
    today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
    return today

Then I began playing around and tried this:

def today(request):
    """Shows todays current time and date."""
    today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
    context = {'today': today}
    return render(request, context)

And this is what I tried adding to the html file:

<h4>{{ today }}</h4>

Update – Trying this and still does not show anything:

def today(request):
    """Shows todays current time and date."""
    today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
    context = {'today': today}
    return render(request, 'learning_logs/topics.html', context)

Advertisement

Answer

If you just want to display only in the template then you can do this

Current datetime:{% now "jS F Y H:i" %}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement