Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display current time using Python + Django?

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() 
like image 681
Lucas Avatar asked Feb 24 '11 20:02

Lucas


People also ask

How does Django use timezone now?

The solution to this problem is to use UTC in the code and use local time only when interacting with end users. Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default.

What is date/time field in Django?

DateTimeField is a date and time field which stores date, represented in Python by a datetime. datetime instance. As the name suggests, this field is used to store an object of datetime created in python.


1 Answers

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

like image 199
AlvaroAV Avatar answered Sep 29 '22 13:09

AlvaroAV