I was not able to get Tom's example to work and it seemed the values were not being modified. However it gave me a starting point and after some reading I found a way to produce 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") #Source must be a models.DateTimeField
class Meta:
model = myModel
fields = ('id', 'ts')
JSON output:
[{
"id": 1,
"ts": 1475894303
},
{
"id": 2,
"ts": 1475833070
}]
[METHOD 2]
Tom's explanation and the previous mentioned method are definitely more on track with maintaining standards (as the results are actually of type integer).
However a quick and dirty solution is to specify the format parameter for the DateTimeField and set it to show the value in seconds.
Note this probably won't work correctly on Windows machines!
And may result in a ValueError: Invalid format string
To try it out just include the "format" keyword parameter in your serializer field like so:
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"
}]
Additionally you may include microseconds:
timestamp = serializers.DateTimeField(format="%s.%f")
If you want to test the functionality in your own interpreter (to verify your OS supports the %s parameter) just copy over these lines:
import datetime
print datetime.datetime.now().strftime('%s') #datetime formatted as seconds for REST
import time #This is just for confirmation
print time.mktime(datetime.datetime.now().timetuple()) #time object result as float
I feel this method is a little inconsistent with the OPs question because the result is not actually of type integer, instead it is a string representation of an integer/float - and REST will surly add quotes around the value.