2

I have configured timezone in Django 1.8 (my current timezone is UTC+1 or BST):

TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True

I have timestamp attribute in my model:

class NodeGPS(models.Model):
    node_id = models.ForeignKey(Node)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    gps_latitude = models.FloatField(null=True, blank=True)
    gps_longitude = models.FloatField(null=True, blank=True)

I have Django Rest Framework 3.4.0, so when I post data through DRF web interface timestamp is set to UTC automatically, which is 1 hour back from my current time (UTC+1). However, in PostgreSQL timestamp field is set as UTC+1. But on DRF web interface it always shows time in UTC.

What a weird behaviour. What is a reason for that?

Thanks in advance for any suggestions!

1 Answers1

3

This is no longer an issue, as django-rest-framework 3.7 and later will now display serialized datetimes with the server's local timezone (set by TIME_ZONE). This is more consistent with django's behaviour of converting to the local timezone in templates and forms.

Before 3.7, datetimes were not automatically converted in serializers (and thus were usually UTC except at object creation, when they were whatever the client uploaded). The assumption was that anyone using the API would be using it through a client with its own way of handling timezones, so the inconsistent behaviour didn't really matter.

If you still need a fix for an old version of DRF, create a custom datetime field that converts to the correct timezone. See here: DjangoRestFramework ModelSerializer DateTimeField only converting to current timezone at object creation

Also: Beware of the PostgreSQL timestamp field. It is merely indicating the times have been converted to the timezone the server thinks it is in, as (from the docs):

All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the timezone configuration parameter before being displayed to the client.

Jonathan Richards
  • 1,414
  • 1
  • 16
  • 20