Reputation: 73
These answers didn't help:
All datetime data is stored in UTC in my database.
I would like each of my users to see the datetime in their local timezone instead of UTC. I've tried the code below:
settings.py
TIME_ZONE = 'UTC'
USE_TZ = True
views.py
from django.shortcuts import render
from home_app import models
from django.utils import timezone
import pytz
def home_view(request):
timezone.activate(pytz.timezone('Asia/Kolkata'))
sample_queryset = models.TimeModel.objects.all()
return render(request, 'home/home.html', {'sample_queryset': sample_queryset,})
home.html
{% for row in sample_queryset %}
{% load tz %}
{% localtime on %}
{{ row.time }}
{% endlocaltime %}
{% endfor %}
models.py
from django.db import models
class TimeModel(models.Model):
sample_text = models.CharField(max_length=255)
time = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.time) + ' ' + self.sample_text
However, after all, the same UTC time from the database is being printed.
Other details:
Django 1.11
SQLite (for now; will use Postgres in production)
Python 3.6.8
Upvotes: 3
Views: 5513
Reputation: 453
Valid timeZone values are based on the tz (timezone) database used by Linux and other Unix systems. The values are strings (xsd:string) in the form “Area/Location,” in which:
Area is a continent or ocean name. Area currently includes:
Location is the city, island, or other regional name.
The zone names and output abbreviations adhere to POSIX (portable operating system interface) UNIX conventions, which uses positive (+) signs west of Greenwich and negative (-) signs east of Greenwich, which is the opposite of what is generally expected. For example, “Etc/GMT+4” corresponds to 4 hours behind UTC (that is, west of Greenwich) rather than 4 hours ahead of UTC (Coordinated Universal Time) (east of Greenwich).
Here is a list all valid timezones
You can change time zone in your settings.py as follows
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Upvotes: 2
Reputation: 73
I have migrated to Postgres from SQLite and made the following changes:
models.py
Before:
from django.db import models
class TimeModel(models.Model):
sample_text = models.CharField(max_length=255)
time = models.DateTimeField(auto_now=True) # changed time to dt
def __str__(self):
return str(self.time) + ' ' + self.sample_text
After:
from django.db import models
class TimeModel(models.Model):
sample_text = models.CharField(max_length=255)
dt = models.DateTimeField(auto_now=True) # changed time to dt
def __str__(self):
return str(self.dt) + ' ' + self.sample_text
Upvotes: 0
Reputation: 1135
The issue looks in your template code, it should be something like
{% for row in sample_queryset %}
{% load tz %}
{% timezone timezone_string %}
{{ row.time }}
{% endtimezone %}
{% endfor %}
I suspect as per here localtime the timezone getting picked up for you is UTC from settings.py You should use this instead timezone
Upvotes: 0