Search code examples
djangodjango-modelspython-datetimedjango-timezone

How to apply timezones to Django Model DateTimeFields


When a Django model contains a DateTimeField the date is always saved in UTC timezone. If you add a date that had a time zone the information is translated and will be retrieved differently. This happens even if the TIME_ZONE has been set in settings.py and the date was created using timezone.localtime(timezone.now()). The same issue happens when the date is added dynamically, like with models.DateTimeField(auto_now_add=True) or models.DateTimeField(auto_now=True).

How can I retrieve or save date times in the correct timezone?


Solution

  • The date may come out in UTC format, but you can always convert it back to your correct timezone.

    from django.conf import settings
    from django.utils import timezone
    
    def getTimezone():
        return pytz.timezone(settings.TIME_ZONE)
    
    model.myDateTimeField.astimezone(getTimezone()) # Converts UTC to the timezone in settings.py
    

    If the datetime was saved in a different timezone altogether, this would not work. Don't do that I guess.