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()
Lucas
  • 1,577
  • 6
  • 18
  • 25

4 Answers4

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

AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
  • The [Time zones](https://docs.djangoproject.com/en/2.2/topics/i18n/timezones/#setup) 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()`](https://github.com/django/django/blob/2.2.1/django/utils/timezone.py#L230) does. Speaking of which, the fact that `timezone.now()` returns time in UTC is counterintuitive. At least at first glance. – x-yuri May 22 '19 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](https://github.com/django/django/blob/2.2.1/django/template/defaulttags.py#L1150) this [automatically](https://github.com/django/django/blob/2.2.1/django/template/defaulttags.py#L374). – x-yuri May 22 '19 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.

Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
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/

Y M
  • 2,105
  • 1
  • 22
  • 44
  • Not quite *so* simple. When time zone support is [enabled](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#naive-and-aware-datetime-objects) (`TZ_INFO=True`), `timezone.now()` returns time in [UTC](https://github.com/django/django/blob/2.2.1/django/utils/timezone.py#L230), but it gets converted to local time in template when [using](https://github.com/django/django/blob/2.2.1/django/template/defaulttags.py#L1150) [now](https://github.com/django/django/blob/2.2.1/django/template/defaulttags.py#L374). – x-yuri May 22 '19 at 10:19
  • You could get the local time in view with timezone.localtime(timezone.now()) – jibin mathew Jun 07 '20 at 06: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.

A B
  • 8,340
  • 2
  • 31
  • 35