1

I'm working on an existing codebase which implements an api using Django and the django-rest-framework. When you post a datetime like this:

2019-06-21T10:35:46+02:00

it is stored in UTC as 2019-06-21 08:35:46+00 (as expected). This is because I've got USE_TZ = True.

When I serve the data, I also want it to be converted to the localised format again (2019-06-21T10:35:46+02:00). So following this tip I implemented it like this:

class DateTimeFieldWihTZ(serializers.DateTimeField):
    """ Class to make output of a DateTime Field timezone aware """
    def to_representation(self, value):
        value = timezone.localtime(value)
        return super(DateTimeFieldWihTZ, self).to_representation(value)


class PeopleMeasurementSerializer(HALSerializer):

    class Meta:
        model = PeopleMeasurement
        fields = [
            '_links',
            'id',
            'timestamp',
            'sensor',
            'count'
        ]

    timestamp = DateTimeFieldWihTZ(format='%Y-%m-%d %H:%M:%S')

But this serves it as 2019-06-21 08:35:46. How can I serve it as 2019-06-21T10:35:46+02:00 again?

kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

0

You need to set TIME_ZONE in your settings.py. It should work out of the box just with putting 'timestamp' in the fields list.

To make it explicit, you could also write

timestamp = serializers.DateTimeField(format='iso-8601')

Note that I'm assuming you're working with one main timezone for all your responses. If you need to return the time with the timezone the user sent, see this answer.

Kevin Languasco
  • 2,318
  • 1
  • 14
  • 20