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)
  • What django version are you using? – alecxe May 4 '13 at 19:13
  • My Django version is 1.5.1. – Cris_Towi May 4 '13 at 21:14
  • Well, it should work right, because Django since 1.4 supports timezones in a right way - so that auto_now_add should just take into account the configured timezone (see docs). Do you have USE_TZ = True in settings? – alecxe May 4 '13 at 21:55
up vote 4 down vote accepted

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

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.