28

I am learning how to use Python and Django to produce a small webapp that prints out the current time. I am using this with the Google App Engine.

Right now it's only displaying a blank page, but I want it to display the current time. I also want to map the function to the home page.. not /time/.

from django.http import HttpResponse
from django.conf.urls.defaults import *
import datetime

# returns current time in html
def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

def main(): 
    # maps url to current_datetime func
    urlpatterns = patterns('',
        (r'^time/$', current_datetime),
    )

if __name__ == '__main__':
  main()
2
  • Are you following any kind of tutorial?
    – Falmarri
    Commented Feb 24, 2011 at 20:57
  • Not any specific tutorial, I am just grabbing things from different places and trying to understand how to write a small webapp using Django.
    – Lucas
    Commented Feb 24, 2011 at 21:19

4 Answers 4

49

Maybe this documentation is useful to you: Time Zones

Formatting time in a view

You can get the current time using:

import datetime
now = datetime.datetime.now()

or to get time depending on timezone:

import datetime
from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)

to format the time you can do:

import datetime

now = datetime.datetime.now().strftime('%H:%M:%S')  #  Time like '23:12:05'

Formatting time in a template

You can send a datetime to the template, let's supose you send a variable called myDate to the template from the view. You could do like this to format this datetime:

{{ myDate | date:"D d M Y"}}  # Format Wed 09 Jan 2008
{{ myDate | date:"SHORT_DATE_FORMAT"}}  # Format 09/01/2008
{{ myDate | date:"d/m/Y"}}  # Format 09/01/2008

Check the Template filter date

I hope this is useful to you

2
  • The Time zones page you're citing recommends enabling time zone support. In this case, the proper way is timezone.now(). Regarding "to get time depending on timezone," you most likely meant "to get time in UTC." And that's what timezone.now() does. Speaking of which, the fact that timezone.now() returns time in UTC is counterintuitive. At least at first glance.
    – x-yuri
    Commented May 22, 2019 at 10:40
  • ...At second one, you might come to realize that that happens because Django keeps time in UTC until it has to present it to the user. That's where conversion happens. Template tags such as now does this automatically.
    – x-yuri
    Commented May 22, 2019 at 10:43
18

Use the now template tag. For example:

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

but you'll need to send your string through template engine before sending the response for it to work.

2
  • 1
    How do you keep getting an updated time though without refreshing the page?
    – Jeff
    Commented Mar 15, 2020 at 20:04
  • @Jeff Django does not dynamically update content on the page, so you would probably want to use Javascript for that. Commented Jun 5, 2021 at 23:57
12

For Django code, not in template the support is actually quite simple.

In settings change the timezone:

TIME_ZONE = 'Asia/Kolkata'

And where you need to use, use the following code:

from django.utils import timezone
now = timezone.now()

Source: https://docs.djangoproject.com/en/2.1/topics/i18n/timezones/

2
  • Not quite so simple. When time zone support is enabled (TZ_INFO=True), timezone.now() returns time in UTC, but it gets converted to local time in template when using now.
    – x-yuri
    Commented May 22, 2019 at 10:19
  • You could get the local time in view with timezone.localtime(timezone.now()) Commented Jun 7, 2020 at 6:33
0

You can use time.strftime() for printing the current time. In your urlpatterns, just change '^time/$' to '^/$' to map the root page to your time function.

Not the answer you're looking for? Browse other questions tagged or ask your own question.