How to show local time in template - python

I'm using PostgreSQL to store an object with a DateTimeField.
The DateTimeField is using auto_now_add options.
And it is created automatically from serializer in Django Rest Framework.
As described in Django docs, I tried to get local timezone and activate it.
from django.utils.timezone import localtime, get_current_timezone
tz = get_current_timezone()
timezone.activate(tz)
session.started_at = localtime(session.started_at)
In template index.html, I also try to load timezone.
{% localtime on %}
Session: start time {{ item.session.started_at }}
{% endlocaltime %}
In settings.py
USE_TZ = True
TIME_ZONE = 'UTC'
I'm using GMT+7 timezone but it still shows UTC time on template.
I'm using Django development server to test.
Am I missing something?

Supposing that all your datetimes are right stored in database as UTC, you can use tz django utility in your template to cast your date to your local time
IE if a datetime is stored as Oct 12, 2017 18:00:00 and i want to convert it to America/La_Paz local time (GMT -4) i can use
Session: start time {{ item.session.started_at|timezone:"America/La_Paz" }}
And in the template will show the local time to America/La_Paz (Oct 12, 2017 14:00:00 in this case)
templates/my_template.html
{% load tz %}
<!-- some html code here -->
Session: start time {{ item.session.started_at|timezone:"America/La_Paz" }}
You can create a cotext var or a var in your view to set the timezone that you wnat to use to cast the date in the tmeplate, ans use it to do the cast
in your view: my_timezone = 'A VALID TIMEZONE NAME'
and again in your template
templates/my_template.html
{% load tz %}
<!-- some html code here -->
Session: start time {{ item.session.started_at|timezone:my_timezone}}

After finding the user's timezone, do this in Django 2 and beyond:
{% load tz %}
{% timezone "Europe/Paris" %}
Paris time: {{ object.date }}
{% endtimezone %}

If I'm not mistaken the TIME_ZONE setting sets the "local" timezone, so change that from UTC to your local time zone.
There is no HTTP-Header that shows the server the client's time zone. Most websites that use localized times ask the user what timezone they are in and save that in the users profile. See Django Documentation
https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/#selecting-the-current-time-zone
Javascript has a way of accessing the UTC offset, maybe you can use that to send the information to your server along with the request.

The users of your webapp may be in different time zones, so the conversion to an appropriate time zone is necessary. You can create a middleware and use activate function to set the current time zone. To get the appropriate time zone you can do an ajax api call to Free IP Geolocation API in your landing page and the time zone value can be saved in a cookie variable which can be later accessed in the middleware.
landingpage.html
<script>
$.ajax({
url: 'https://freegeoip.app/json/',
dataType: 'json',
success: function (data) {
document.cookie = 'timezone=' + data['time_zone'] + '; path=/';
}
});
</script>
middleware.py
import pytz
import requests
from django.utils import timezone
class TimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
tzname = request.COOKIES.get('timezone')
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
return self.get_response(request)
settings.py
MIDDLEWARE = [ ........
'projectname.middleware.TimezoneMiddleware',
]

Related

Problem with Django query on Elastic Beanstalk

I've met a problem with my Django query. So, I have a filter like this.
Discount.objects.filter(end_date__gte=date.today()) #end_date is DateField
It works properly on my localhost. But, on the server that I deployed with Elastic Beanstalk, it still returns yesterday's records. And, when I redeploy the server (without any changes), it works fine, yesterday's records have been filtered and hided.
I tried but can't find where is the problem. Hope anyone can help me.
Thank you all.
Django often times will handle timezones on the view for you, but within the backend you can run into time discrepancies with the server time vs local time to your user(the view)
One thing that can help is to setup your django timezone settings.py:
TIME_ZONE = 'America/Chicago'
USE_TZ = True
If you are still running into issues of local-time not matching server time you can do some translations to the time.
from django.utils import timezone
to_tz = timezone.get_default_timezone()
import datetime
Discount.objects.filter(end_date__gte=datetime.datetime.today().astimezone(to_tz))
Test in shell by running: python manage.py shell
from django.utils import timezone
from app.models import Discount
to_tz = timezone.get_default_timezone()
import datetime
print(f"Today is: {datetime.datetime.today().astimezone(to_tz)}")
todays_discounts = Discount.objects.filter(end_date__gte=datetime.datetime.today().astimezone(to_tz))
for each in todays_discounts:
print(f"{each} date:{each.end_date}")
Managing timezones in the template:
{% load tz %}
<!-- some html code here -->
Date: {{ context.object.end_date|timezone:"America/La_Paz" }}
or
{% load tz %}
{% timezone "Europe/Paris" %}
Date: {{ context.object.date }}
{% endtimezone %}

Django timezone.now().time displays incorrect time zone

The subject is the simplest way that I can break down the problem that I am getting.
I'm using Django 2.1
settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True
views.py
message = timezone.now().time
message2 = timezone.now
The above code is the fastest way to show the problem that I have. When I print 'message' I'm given a time different than what I get from 'message2' although they are both pulling the same value.
My model saves a datetimefield using the auto_now_add feature.
models.py
class Comment(models.Model):
date_time = models.DateTimeField(auto_now_add=True, blank=True)
When I display the field in HTML as
{{ comment.date_time }}
the correct date and time appears. However when I use my own formatting and break up the code as
{{ comment.date_time.date }}: {{ comment.date_time.time }}
then I cannot get the time to display in the correct timezone. I've tried the following alterations all to no avail.
{% load tz %}
{% localtime on %}
{{ comment.date_time.time }}
{% endlocaltime %}
{{ comment.date_time.time|localtime }}
{{ comment.date_time.time|timezone:"America/New_York" }}
Does anyone know of a way to address this?
Try this,
pass timezone.now() to timezone.localtime
from django.utils import timezone
timezone.localtime(timezone.now())
More info here.
The problem is that you're using trying to use time objects instead of datetime objects. The localtime and timezone template tags and filters are expecting datetime objects.
If you want a custom format in the template, use the date filter. If for whatever reason that can't give you the format you want, you will need to do the conversion yourself in the view rather than relying on the template, e.g.:
from django.utils.timezone import localtime
def view():
local = localtime(comment.date_time)
date_string = str(local.date()) # or whatever custom format you want
time_string = str(local.time()) # or whatever custom format you want
from django.utils import timezone
timezone.localtime(timezone.now())
Also, in the settings.py you must change:
TIME_ZONE = 'America/New_York'
A list of the time zone database names can be found on: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Setting Django admin display times to local time?

When I see dates and times in the admin, they are displayed in UTC. I'd like for them to be displayed in my local timezone. I checked the TIME_ZONE setting in the docs, though it doesn't look like that is quite what I want. TIME_ZONE determines the time zone for the datetimes stored in the database, which is not what I want to set -- I just want to localize the time zones for the admin, but not change how they are saved at the database level.
Is there a way to do this?
In Django:
The default time zone is the time zone defined by the TIME_ZONE setting.
The current time zone is the time zone that’s used for rendering.
so you should set the "current time zone" use:
django.utils.timezone.activate(timezone)
You can activate it in a middleware(don't forger to register it to MIDDLEWARE in settings.py):
import pytz
from django.utils import timezone
class TimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
timezone.activate(pytz.timezone('Asia/Shanghai')
return self.get_response(request)
This is only a simple hardcode. you can making a form to select tzinfo, store it in user's profile and load it to user session, read the tzinfo from the session in the middleware.
The official documentation has a related description:
https://docs.djangoproject.com/en/3.0/topics/i18n/timezones/#selecting-the-current-time-zone
Reference:
https://groups.google.com/forum/#!topic/django-developers/E4aiv3O6vGo
This isn't supported natively in Django as of 2.1. However https://github.com/charettes/django-sundial may provide what you need -- this adds a User.timezone model field so that you can configure it per-user.
(This middleware is very simple -- under the covers it's just calling timezone.activate(zone) to change the rendered site's timezone).
You can override the template for your change_list.html, change_form.html, etc. and do something like:
{% extends "admin/change_list.html" %}
{% load tz %}
{% block content %}
{% timezone "US/Eastern" %}
{{ block.super }}
{% endtimezone %}
{% endblock %}
Do it with one of those methods:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#admin-overriding-templates
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#custom-template-options
Maybe you can try to set user timezone.
Set
USE_TZ = True
Official documentation

datetime fields are saved with different values and show different values in forms django

I have a model that has a DateTimeField in it.
class Event(models.Model):
.....
date = models.DateTimeField()
and a model form for this event
class EventForm(ModelForm):
class Meta:
model= Event
When I create an event from admin I set the time to the time I want the event to occure, let's say 19:30. But if I call the events.date property I get
event.date
datetime.datetime(2013, 11, 20, 17, 30, tzinfo=<UTC>)
If I use it in a template like
{{event.date.hour}}:{{event.date.minute}}
it shows 17:30.
But when i load it on template within the model form
event_form = EventForm(instance=event)
and in template
{{event_form.as_p}}
then the date renders the same as I added it in the admin page, that is 19:30
How can I change this behavour. Does django always save in UTC the dates? I am in Greece hence the minus 2 hours (I think) of the datetime object. Supposingly my app will run in many different countries, can I automate this, like when I render the date on a template using the property it will show the time that was actually saved and not the time in UTC. Hope I am making sense....
In my settings file i have
TIME_ZONE = 'Europe/Athens'
USE_TZ = True
If you want time zone per user, you need to store that in your user profiles or something like that. And then use that information to convert user entered time to appropriate UTC to store.
Without that you are storing the times as per the timezone set on your server. So if some user in GMT, selects time as 0800, it will be actually 0800 in Athens not in GMT.
In template you can do
{% load tz %}
{% timezone get_current_users_timezone %}
{{ event.date }}
{% endtimezone %}
Refer django timezones for details info.

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)

Categories