I was unable to get the Tom example to work, and it seemed like the values ββweren't changing. However, this gave me a starting point, and after some reading, I found a way to get the desired result:
[METHOD 1]
serializers.py
import time class TimestampField(serializers.Field): def to_representation(self, value): return int(time.mktime(value.timetuple())) class MySerializer(serializers.ModelSerializer): ts = TimestampField(source="my_fieldname")
JSON Output:
[{ "id": 1, "ts": 1475894303 }, { "id": 2, "ts": 1475833070 }]
[METHOD 2]
Explanation Tom and the previous method are certainly more consistent with standards-compliant tracks (since the results are actually of type integer).
However, a quick and dirty solution is to specify a format parameter for DateTimeField and set it to display the value in seconds.
Please note that this probably won't work on Windows machines! And can lead to the creation of a ValueError string: Invalid format
To try, just include the "format" keyword parameter in your serializer field, for example:
serializers.py
class MySerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField(format="%s") class Meta: model = myModel fields = ('id', 'ts')
JSON Output:
[{ "id": 1, "ts": "1475890361" }, { "id": 2, "ts": "1475833070" }]
Alternatively, you can enable microseconds:
timestamp = serializers.DateTimeField(format="%s.%f")
If you want to test the functionality of your own interpreter (to check if your OS supports the% s parameter), just copy these lines:
import datetime print datetime.datetime.now().strftime('%s')
I feel that this method is a bit incompatible with the OPs question, because the result is not an integer, but a string representation of the integer / float - and REST will unnecessarily add quotes around the value.