How do I display current time using Python + Django? - python

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()

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

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.

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/

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.

Related

Can SQLAlchemy Date Time object display local time zone in Flask

This is my first Stackoverflow post, pardon my syntax.
I am trying to have a time stamp in date timestamp without time zone in a SQLAlchemy database display the time in the user's browser with the time in the their timezone, not UTC.
Here is my python/Flask code (I'm a beginner):
First I query the database
timeclockinfo = TimeClock.query.filter_by(parent_id=current_user.parent_id, user_id=current_user.user_id, closed=1).all()
#Then I tuple the data
child_patient = zip(timeclockinfo, user_names, visit_dates )
#I render the data with Flask
return render_template('locationcheckinrpt.html', form=form, child_patient=child_patient, timeclockinfo=timeclockinfo, searchForm=searchForm)
.
.
.
#In the template I have a date time field for the records rendered
{% for times in child_time %}
{{ times[0].checkintime.strftime('%Y/%m/%d # %I:%M %p') }}
{% endfor %}
Can anyone advise me on how to have the UTC times[0].checkintime display in the browser users timezone and not UTC.
I do have the User enter their time zone so I subtract the appropriate number of hours.
But, I cannot hack my way through getting this to display.
If you have the datetime and the user's time zone, you could create a template filter that takes a datetime object, does the required computation, and then prints the string.
If your questions is about actually about applying a time zone to a naive datetime object, then take a look at pytz (relevant section):
from datetime import datetime
from pytz import timezone
tz = timezone('saved_user_timezone')
dt = saved_time_from_db
locl_dt = tz.localize(dt)
To display the datetime with the timezone offset, try:
local_dt.replace(hour=local_dt.hour + int(local_dt.utcoffset().total_seconds() / 3600))
local_dt.strftime('your format')

Generating a date relative to another date in Django template

I have a date in my template context, and I want to display that date plus 7 days in the rendered output.
Something like this (which does not exist):
{{some_date|plus_days:7}}
How can I do this in a Django template without writing any Python code?
You can create your own template tag:
import datetime
from django import template
register = template.Library()
#register.filter
def plus_days(value, days):
return value + datetime.timedelta(days=days)
This cannot be done in Django templates as of this writing without writing a custom template tag in Python.

print page generation time

how would I print the time it took to render a page to the bottom of my site in django? i'm not sure of the application flow of django, so I don't know how this would work.
You might be interested in django-debug-toolbar, which includes a request timer and lots of other useful info for debugging things like this.
At the beginning of your view handler, save the current date/time in a variable say time_start and pass that to the template context which renders the page.
Then define a custom template filter that will create timedelta based on datetime.now() value and the original datetime passed in as a parameter like so:
from datetime import datetime
from django import template
register = template.Library()
#register.filter
def get_elapsed(time_start):
return str(datetime.now() - time_start)
Then in your template, simply display:
...
{{ time_start|get_elapsed }}
...

How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?

I understand that the best practice now with Django 1.4 is to store all datetime in UTC and I agree with that. I also understand that all timezone conversation should be done in the template level like this:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ value }}
{% endtimezone %}
However, I need to convert the UTC time to the request's local time all in Python. I can't use the template tags since I am returning the string in JSON using Ajax (more specifically Dajaxice).
Currently this is my code ajax.py:
# checked is from the checkbox's this.value (Javascript).
datetime = timezone.now() if checked else None
$ order_pk is sent to the Ajax function.
order = Order.objects.get(pk=order_pk)
order.time = datetime
order.save()
return simplejson.dumps({
'error': False,
'datetime': dateformat.format(datetime, 'F j, Y, P') if checked else 'None'
})
So even if the current time is April 14, 2012, 5:52 p.m. in EST time (my local timezone), the JSON response will return April 14, 2012, 9:52 p.m, because that is the UTC time.
Also I noticed that Django stores a template variable called TIME_ZONE for each request (not actually part of the request variable), so since my is America/New_York, I'm assuming that Django can figure out each visitor's own local timezone (based on HTTP header)?
Anyway, so my question is two-fold:
How do I get the visitor's local timezone in my ajax.py? (Probably pass it as a string argument like {{ TIME_ZONE }})
With the visitor's local timezone, how to convert the UTC timezone.now() to the local timezone and output as a string using Django's dateformat?
EDIT: for #agf
timezone.now() gives the UTC time when USE_TZ = True:
# From django.utils.timezone
def now():
"""
Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
Is there anyway to convert a datetime to something other than UTC? For example, can I do something like current_time = timezone.now(), then current_time.replace(tzinfo=est) (EST = Eastern Standard Time)?
You need to read the Django Timezones docs carefully.
One important point:
there's no equivalent of the Accept-Language HTTP header that Django could use to determine the user's time zone automatically.
You have to ask the user what their timezone is or just use a default.
You also need to make sure:
USE_TZ = True
in your settings.py.
Once you have a timezone tz, you can:
from django.utils import timezone
timezone.activate(tz)
datetime = timezone.now() if checked else None
to get a timezone-aware datetime object in timezone tz.
While the browser does not send any headers to the server that would indicate a timezone, the JavaScript environment does know its current timezone.
This has two important effects: While the server can't find out your current timezone on the initial request, you can send down some javascript code which will determine the TZ offset and send that information back to the server so that the zone info can be associated with the current session from that point forward.
But more importantly, if you're sending your time value inside JSON data which will be interpreted by the browser client-side, the browser's timezone doesn't need to be known. Instead, you only have to ensure the timezone offset is present in your JSON output so that the browser can do its own timezone math after-the-fact.
var now = new Date()
var offset_minutes = now.getTimezoneOffset() # e.g. 240 for GMT-0400
Since you want the users' timezones, it makes sense to me that this should be done on the browser with Javascript.
I pass something like this into the template:
{"t": str(obj.timestamp))
Where obj is an instance of a django model where the timestamp field is of type DateTimeField.
The template:
<div class="timestring">{{ t }}</div>
...
<script>
$('.timestring').each(function(){
var d = new Date($(this).text());
$(this).text(d.toLocaleDateString() + ", " + d.toLocaleFormat("%r (%Z)"));
})
</script>
For me, this outputs something like: 2/15/2017, 05:22:24 PM (PST)
The relevant documentation:
Javascript Date class (see especially the constructor which accepts datestrings, and the toLocaleFormat() method)
strftime (comes with lots of date formatting shortcuts)

Calculate number of days between two dates inside Django templates

I have two dates and want to show a message like "n days left before your trial end." where n is a number of days between two given dates. Is that better to do this inside views or is there a quick way to do it inside template itself?
Use timesince template tag.
This code for HTML in Django. You can easily find the remaining days.
{{ to_date|timeuntil:from_date }}
Otherwise, you can use custom TemplateTags.
Possible duplicate here
I'd actually use the same method lazerscience uses, something like this:
from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince
register = template.Library()
#register.filter
def time_until(value):
now = datetime.now()
try:
difference = value - now
except:
return value
if difference <= timedelta(minutes=1):
return 'just now'
return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}
In the HTML template, you can do the following:
{{ comments.created|timeuntil:project.created }}
And you get output something like this:
1 hour, 5 minutes

Categories