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"
Convert the datetime object into timestamp using datetime. timestamp() method. We will get the timestamp in seconds. Round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds.
In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function. Returns : It returns the string representation of the date or time object. Code: Python3.
You can get timestamp from a datetime object using datetime. timestamp() method.
Get Current Time in PythonUse the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00. It returns the current time in seconds.
REST_FRAMEWORK = {
# if you want with milliseconds or
'DATETIME_FORMAT': '%s.%f',
# only with seconds
'DATETIME_FORMAT': '%s',
}
Result in REST will be string
"1517863184.666435"
"1517863249"
If you want float(or integer) value in API, than you can use monkey patching.
Put the file monkey_patching.py
in any of your apps
and import it in app's __init__.py
file. ie:
app/monkey_patching.py
#app/monkey_patching.py
import six
from rest_framework import ISO_8601
from rest_framework.fields import DateTimeField
from rest_framework.settings import api_settings
def to_representation_ext(self, value):
if not value:
return None
output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT)
if output_format is None or isinstance(value, six.string_types):
return value
if output_format.lower() == ISO_8601:
value = self.enforce_timezone(value)
value = value.isoformat()
if value.endswith('+00:00'):
value = value[:-6] + 'Z'
return value
# FOR INTEGER RESULT 'DATETIME_FORMAT': '%s',
# return int(value.strftime(output_format))
# FOR FLOAT RESULT 'DATETIME_FORMAT': '%s.%f',
return float(value.strftime(output_format))
DateTimeField.to_representation = to_representation_ext
app/init.py
#app/__init__.py
import app.monkey_patching
Tested with Django version 2.0.10 and Python 3.5.9
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()
.
EDIT for DRF 3.x & Python 3.8:
class TimestampField(serializers.Field):
def to_representation(self, value):
return value.timestamp()
If you want a JavaScript style timestamp:
class JsTimestampField(serializers.Field):
def to_representation(self, value):
return round(value.timestamp()*1000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With