Posts /

Restframework 에서의 Timestamp 변환을 위한 Customfield

06 Jul 2018

소개

Code

from django.utils import timezone
from rest_framework import serializers


class DateToTimestampField(serializers.Field):
    def to_representation(self, value):
        epoch = timezone.datetime(1970, 1, 1)
        value = timezone.datetime.fromordinal(value.toordinal())
        return int((value - epoch).total_seconds())


class DatetimeToTimestampField(serializers.Field):
    def to_representation(self, value):
        epoch = timezone.datetime(1970, 1, 1)
        return int((value - epoch).total_seconds())

Twitter Facebook Google+