Cris_Towi
Cris_Towi

Reputation: 625

models.DateTimeField(auto_now_add = True)

I have a problem with my models.DateTimeField, because I´m from México and in settings.py I use this:

TIME_ZONE = 'America/Mexico_City'

But when i add a register in my mysql database, it says that the register added at 18:00 (4 hours later, because here, in Mexico City is 14:00)

titulo = models.CharField(max_length = 60)
contenido = models.CharField(max_length = 140)
fecha = models.DateTimeField(auto_now_add = True)

Upvotes: 0

Views: 3161

Answers (1)

MaestroFJP
MaestroFJP

Reputation: 376

If you enable USE_TZ = True, Django then uses UTC for all times in the database. That is why you are seeing the time 4 hours ahead -- that is UTC time.

https://docs.djangoproject.com/en/dev/topics/i18n/timezones/

Django has helpers to take the UTC and then convert it back for you when you display it in a view. Try getting an object from the db that uses DateTimeField and try this in a view where {{ value }} is the datetime:

{% load tz %}

{% localtime on %}
    {{ value }}
{% endlocaltime %}

{% localtime off %}
    {{ value }}
{% endlocaltime %}

You might have install pytz as a requirement if you haven't done so already:

pip install pytz

Upvotes: 4

Related Questions