Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model's DateTimeField is taking UTC even when timezone is Asia/Calcutta everywhere

I am using Django 1.11. My settings.py has following configured:

TIME_ZONE = 'Asia/Calcutta'
USE_I18N = True
USE_L10N = True
USE_TZ = True

which is IST (Indian Standard Time). My system is set to IST. MySQL current_time returns IST, Django's server when running, shows timestamp in IST. Python's datetime.now() also gives IST.

Now the problem is, my models.py has following fields:

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

and the database is MySQL. When I insert any record in it, the timestamps are in UTC. I was thinking of adding some middleware, as suggested by this answer, but that doesn't feel to be the recommended way. Why is it taking UTC even when everywhere IST has been configured? Am I missing some config that needs to be set separately for models?

Please note that this question is not similar to what I require. I want to change the overall timezone, so that it is effective in model's too.

like image 893
Rakmo Avatar asked Mar 22 '18 09:03

Rakmo


1 Answers

datetimes will always be stored in UTC if USE_TZ is True.

The only way around that is to set USE_TZ to False. auto_now uses django.utils.timezone.now(), which is defined to do the following:

If USE_TZ is False, this will be a naive datetime (i.e. a datetime without an associated timezone) that represents the current time in the system’s local timezone.

Which sounds like what you're asking for.

But are you sure that's what you want? Since Asia/Calcutta had DST in the past there will be times that you simply can't represent unambiguously in the database. That's why UTC is the standard choice for storing datetimes.

like image 185
Kevin Christopher Henry Avatar answered Oct 10 '22 21:10

Kevin Christopher Henry