[Answered ]-Django, Python datetime.now() and storing the timezones

2👍

Django ORM stores date time in your SQL database’s corresponding field. The underlying SQL column is determined by the used database. E.g. for MySQL, the mappings are defined here:

https://github.com/django/django/blob/master/django/db/backends/mysql/creation.py#L16

Conversion from Django to SQL:

https://github.com/django/django/blob/master/django/db/backends/mysql/base.py#L272

Conversion from SQL to Django:

https://github.com/django/django/blob/master/django/db/models/fields/init.py#L1186

Python datetime.datetime.now() is so-called timezone-naive datetime and doesn’t have any timezone information. Thus, you may lose information when storing times with it and it’s usage is discouraged. It returns the local time. It seems that that if timezone information is omitted, the Django USE_TZ setting determines if the default timezone information is retrofitted internally.

Instead, you should use django.utils.timezone.now() (local time with timezone) or django.utils.timezone.utcnow() (time with UTC timezone).

More info

https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#naive-and-aware-datetime-objects

Leave a comment