Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework updating time using EPOCH time

I need to take a form that has a field "starttime" that is in EPOCH and convert it to

  1. python datetime
  2. fieldname = "created"

when I have:

models.py

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True

    class Meta:
        ordering = ('created',)

serializers.py

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.

like image 486
user1639926 Avatar asked Oct 15 '13 07:10

user1639926


2 Answers

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')
like image 164
Kevin Stone Avatar answered Sep 20 '22 23:09

Kevin Stone


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))
like image 23
Diviei Avatar answered Sep 17 '22 23:09

Diviei