Muser
Muser

Reputation: 603

Problem with timezone in Django ORM, datetime value differs from the value stored in the table

I have stored some data into PostgreSQL database. Here is the corresponding Django model:

from django.contrib.gis.db import models

class PrecipitationContourDjango10d(models.Model):
    value = models.FloatField(blank=True, null=True)
    geometry = models.PolygonField(blank=True, null=True)
    date = models.DateTimeField(blank=True, null=True)
    window_no = models.CharField(max_length=10, blank=True, null=True)
    color = models.CharField(max_length=20, blank=True, null=True)

    def __lt__(self, other):
        if self.date < other.date:
            return True
        return False

    class Meta:
        db_table = 'precipitation_contour_web_service10d'

Here is some rows that are stored in the table: enter image description here

As you can see the datetime value for the row with id=5921 is 2021-05-07 21:00:00-07. However when I retrieve that row using the Django ORM, its datetime field will change:

from data.models import PrecipitationContourDjango10d
row = PrecipitationContourDjango10d.objects.get(id=5921)

enter image description here

Any help would be highly appreciated. Thanks.

Upvotes: 0

Views: 178

Answers (2)

AlexTorx
AlexTorx

Reputation: 775

You must be aware that the second result you provided does not mention any timezone. It may have an hidden timezone based on your system preference. This does not mean they are different.

For instance : '2021-05-07 21:00:00-07' and '2021-05-07 23:00:00-05' actually are the same datetimes, expressed in two different timezones (i.e the same moments but expressed in the local time of two different places in the world).

EDIT : Set USE_TZ=True in django config file for a consistent use of timezone aware datetime (see https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/).

Upvotes: 0

user1600649
user1600649

Reputation:

It is not an issue. This is how things work when USE_TZ is False:

  • Your Postgres has timezone set to UTC-7 (for example US/Pacific), either through config or machine time, and this is what your client is showing
  • Your Django has timezone set to UTC-5 (for example US/Central), either through config or machine time and datetimes are translated to naive datetimes in Django's timezone

If working with timezones is important to you, you should read the topic in the documentation carefully and enable USE_TZ:

When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

This is handy if your users live in more than one time zone and you want to display datetime information according to each user’s wall clock.

Upvotes: 1

Related Questions