elewinso elewinso - 1 year ago 113
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


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download