Skip to content

Timestamp to DateTime Serializer Field for DRF

September 29th, 2017 - SoftwareTutorial(1 min)

I’m currently trying to deserialize JSON data to a Django model. This is quite straight forward for most numeric fields, but I have a DateTime field which is stored as a timestamp in the original JSON.

At first, I thought I should read the timestamp as an integer and convert it through post-processing. Then, after reading more of the DRF docs, it became evident I needed a custom field. The code is below:

from rest_framework import serializers
from datetime import datetime

class TimestampField(serializers.DateTimeField):
    Convert a django datetime to/from timestamp.
    def to_representation(self, value):
        Convert the field to its internal representation (aka timestamp)
        :param value: the DateTime value
        :return: a UTC timestamp integer
        result = super(TimestampField, self).to_representation(value)
        return result.timestamp()

    def to_internal_value(self, value):
        deserialize a timestamp to a DateTime value
        :param value: the timestamp value
        :return: a django DateTime value
        converted = datetime.fromtimestamp(float('%s' % value))
        return super(TimestampField, self).to_representation(converted)

The idea is that to_representation converts a DateTime field into a timestamp value for serialisation and to_internal_value does exactly the opposite:

  • to_representation: just gets the timestamp() value out of the DateTime field

  • to_internal_value: converts the timestamp value to a DateTime object via:

    datetime.fromtimestamp(float('%s' % value))

This is all!


Share on

A little experiment: