Django 1.7, PostgreSQL.
I want to store datetime in UTC and display it in PST time zone.
My 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 have created new model, and in django admin it display PST time (6:05 pm). It is OK. But if I do:
select created_at from my_table where id = 1;
It display my local time (8:05 am)! So, I'm not sure that this was stored in UTC time.
And one more thing.
Usual datetime field, I have set in admin this date: 2014-10-25 18:00:00
Id displayed in admin Oct. 25, 2014, 6 p.m.
But select from DB show me:
2014-10-26 08:00:00.0
So, I definitely do not understand what's going on. Where is my mistake?
Basically what happens is that time is stored in database using the timestamp, but displays the time using timezone specified in your database, which is unless manually changed is the timezone of the machine. But since you specify a different timezone in django, django will adjust the difference. So what you need to do is change the timezone in db to UTC (process differs depending on the engine)
The way I prefer to do it is leaving database timezone unchanged, specify 'UTC' in django settings, and then whenever displaying time to user, using some javascript convert it to local users time.
Edit
Didn't notice before that you are using PostgreSQL. I think you can just change timezone in postgresql.conf or change the TimeZone variable to UTC in database