Serialize datetime as an integer timestamp

I would like django rest not to convert my DateTime model field to a string representation of the date when it is serialized.

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

I wish it came out like

1411880508

but not

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

+8
python django-rest-framework
source share
5 answers

You will want to write a custom serializer field , for example:

 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 that you would like to inherit from WritableField , as well as implement from_native() .

+8
source share

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") #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]

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') #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 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.

+3
source share

Global configuration:

 REST_FRAMEWORK = { 'DATETIME_FORMAT': '%s.%f', } 
+2
source share

Although I prefer the answer given by Tom Christie, as it is more reliable. I decided to publish my decision in the interests of potential readers.

 response_date = serializers.SerializerMethodField('get_timestamp') def get_timestamp(self, obj): #times 1000 for javascript. return time.mktime(obj.updated_at.timetuple()) * 1000 
+1
source share
 REST_FRAMEWORK = { # if you want with milliseconds or 'DATETIME_FORMAT': '%s.%f', # only with seconds 'DATETIME_FORMAT': '%s', } 

REST result will be

1) 1517863184.666435

2) 1517863249

+1
source share

All Articles