I need to take a form that has a field "starttime" that is in EPOCH and convert it to
when I have:
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True
class Meta:
ordering = ('created',)
import time
class SnippetSerializer(serializers.ModelSerializer):
starttime = serializers.SerializerMethodField('epoch')
def epoch(self, obj):
""" Return epoch time for a datetime object or ``None``"""
try:
return int(time.mktime(obj.created.timetuple()))
except (AttributeError, TypeError):
return None
class Meta:
model = Snippet
fields = ('starttime')
If I:
"GET" /snippets/1/
{"id":1, 'starttime':13232111}
I want to be able to do:
"POST" /snippets/1/ {"id":1, 'starttime':1}
{"id":1, 'starttime':1}
right now, it just ignores the request. I am forced to use unix epoch times to conform to existing API's.
You want to write your own serializer Field sub-class with overridden to_native()
and from_native()
for the actual conversion. Here's my attempt:
class UnixEpochDateField(serializers.DateTimeField):
def to_native(self, value):
""" Return epoch time for a datetime object or ``None``"""
import time
try:
return int(time.mktime(value.timetuple()))
except (AttributeError, TypeError):
return None
def from_native(self, value):
import datetime
return datetime.datetime.fromtimestamp(int(value))
And then use that field in your Serializer
definition:
class SnippetSerializer(serializers.ModelSerializer):
starttime = UnixEpochDateField(source='created')
Adapting Kevin Stone code for Django Rest Framework 3:
class UnixEpochDateField(serializers.DateTimeField):
def to_representation(self, value):
""" Return epoch time for a datetime object or ``None``"""
import time
try:
return int(time.mktime(value.timetuple()))
except (AttributeError, TypeError):
return None
def to_internal_value(self, value):
import datetime
return datetime.datetime.fromtimestamp(int(value))
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