elewinso elewinso - 1 month ago 11
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


1411880508


and not


"2014-09-28T05:01:48.123"

Answer

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().