Python / Django MySQL Handling Time and Time

I have a model called Vote with a date field:

 date = models.DateTimeField(auto_now_add=True) 

When I add an item, the date in MySQL is a UTC date, but I live in UTC + 2 time zone

I think I set the time zone correctly in settings.py :

 TIME_ZONE = 'Europe/Paris' 

Python uses the correct time zone:

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

MySQL too:

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

I can set the date attribute manually, it works, but I would like to know why auto_now_add returns the wrong date, although python and mysql use the correct time zone

thanks

+4
python timezone django mysql datetime
source share
1 answer

This is a complex reference for explanation. From Django 1.4 ,

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

this one is for TIME_ZONE . So what is your USE_TZ ? If your USE_TZ is True, then Django will store the date and time in UTC and use TIME_ZONE to display in the templates and interpret the forms.

This is due to the fact that if you change your TIME_ZONE later when placing your site in another territory, it is easy to convert any data from UTC to any given time intervals.

In Django 1.3 and earlier

Note that this is the time zone to which Django will convert all dates / times - not necessarily the time zone of the server. For example, one server can serve several Django-based sites, each of which has its own time zone setting.

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

But it won’t tell you what time datetime will be stored in the database. You need to experiment in any case (my guess is UTC).

print datetime.datetime.now() prints the date according to the time zone setting of your server, if you did not open the python console through manage.py shell .

The same goes for the MySQL console. It shows the time and time in the time zone of your computer, and not what is stored in the database, if I'm right.

+9
source share

All Articles