elewinso elewinso - 3 months ago 21
Python Question

serialize a datetime as an integer timestamp

I would like for django rest to not convert my DateTime model field into a string date represtation when serializing it.

response_date = serializers.DateTimeField(source="updated_at")

I would like this to come out as


and not



You'll want to write a custom serializer field, like so:

class TimestampField(serializers.Field):
    def to_native(self, value):
        epoch = datetime.datetime(1970,1,1)
        return int((value - epoch).total_seconds())

To support write operations you'd want to inherit from WritableField and also implement from_native().