Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and time zone

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?

like image 742
Tom Avatar asked Oct 25 '14 01:10

Tom


People also ask

How does Django handle time zones?

Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default. Time zone support uses zoneinfo , which is part of the Python standard library from Python 3.9.

What is the default timezone setting in Django?

TIME_ZONE in Django The default timezone is TIME_ZONE = 'UTC' . TIME_ZONE = 'Asia/Calcutta' . For applying these changes we need to set the USE_TZ variable to TRUE.

What timezone is UTC?

Prior to 1972, this time was called Greenwich Mean Time (GMT) but is now referred to as Coordinated Universal Time or Universal Time Coordinated (UTC). It is a coordinated time scale, maintained by the Bureau International des Poids et Mesures (BIPM). It is also known as "Z time" or "Zulu Time".


1 Answers

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

like image 115
lehins Avatar answered Oct 13 '22 01:10

lehins