Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Django MySQL Datetime handling and timezone

I've got a model called Vote with a field date :

date = models.DateTimeField(auto_now_add=True)

When I add an element, the date in MySQL is an UTC date but I live in UTC+2 timezone

I think I correctly set the timezone in settings.py :

TIME_ZONE = 'Europe/Paris'

Python use the right timezone :

>>> print datetime.datetime.now()
2013-07-03 09:05:04.474000

MySQL too :

> SELECT NOW( )
2013-07-03 09:00:48

I could set the date attribute manualy, it works but I would like to know why auto_now_add return a wrong date although python and mysql use the right timezone

Thank you

like image 501
Thomas K Avatar asked Dec 26 '22 00:12

Thomas K


1 Answers

It's a complex binding to explain. From Django 1.4,

When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms.

this refers to TIME_ZONE. So what is your USE_TZ? If your USE_TZ is True then Django will store datetime in UTC and use TIME_ZONE to display in templates and interpret forms.

This is because, if you change your TIME_ZONE later when hosting your site in another territory, it's easy to convert any datetimes from UTC to any timezones given.

In Django 1.3 and earlier,

Note that this is the time zone to which Django will convert all dates/times – not necessarily the timezone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time-zone setting.

Normally, Django sets the os.environ['TZ'] variable to the time zone you specify in the TIME_ZONE setting. Thus, all your views and models will automatically operate in the correct time zone.

But doesn't tell you in what timezone the datetime will be stored in database. Need to experiment anyway(my guess is UTC).

print datetime.datetime.now() prints the datatime according to the timezone setup of your server machine unless you have opened the python console via manage.py shell.

Same goes for MySQL console. It shows the datetime in your machine timezone rather than what's stored in database if I'm right.

like image 190
Babu Avatar answered Jan 04 '23 15:01

Babu