Django and timezone

Django 1.7, PostgreSQL.

I want to store date and time in UTC and display it in PST timezone.

Local time: 8:05 am

UTC time: 1:05 am

PST time: 6:05 pm

Django doc:

When support for time zones is enabled, Django stores date and time 
information in UTC in the database, uses time-zone-aware datetime objects 
internally, and translates them to the end user’s time zone in templates 
and forms.

      

setting.py

USE_TZ = True
TIME_ZONE = 'US/Pacific'

      

Model field

created_at = models.DateTimeField(auto_now_add=True)

      

I created a new model and in django admin it displays PST time (6:05 pm). Things are good. But if I do this:

select created_at from my_table where id = 1;

      

Shows my local time (8:05)! So, I'm not sure if this was stored in UTC.

And one more thing.

Normal datetime field, I set in admin this date: 2014-10-25 18:00:00

Id displayed in admin Oct. 25 , 2014, 6 pp.

But choose from DB, show me:

2014-10- 26 08: 00: 00.0

So, I definitely don't understand what's going on. Where is my mistake?

+3


source to share


2 answers


What basically happens is that the time is stored in the database using a timestamp, but it displays the time using the timezone specified in your database, unless manually changed it is the machine's timezone. But since you are specifying a different timezone in django, django will adjust the difference. So what you need to do is change the timezone in db to UTC (the process is different depending on the engine)

The way I prefer to do this is to leave the database timezone unchanged, specify "UTC" in django settings, and then whenever you show the time to the user using some javascript, convert it to the user's local time.



Edit

Didn't notice that you are using PostgreSQL. I think you can just change the timezone in postgresql.conf or change the TimeZone variable to UTC in the database

+5


source


I think Aleksey Kuleshevich answers the first part of your question: when you do the manual select

, PostgreSQL displays the timestamp in the timezone configured in the database. This does not affect Django, although it behaves according to the documentation.



Regarding the second part of your question, when you enter a datetime value on a form, Django interprets it in the current timezone, which is the default setting TIME_ZONE

. So when you enter 18:00 into the admin, Django interprets that as 6pm PST and stores it as 1am UTC (the next day). The database then displays this as 8am local time (the next day).

0


source







All Articles