Last active
June 27, 2022 15:42
-
-
Save hammadzz/fe8f35c4b4344dd6ce9f73d23e825c96 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Django 10.1 on Python 3.5 | |
#main credit to http://stackoverflow.com/users/2089197/kevin-stone | |
#sub credit to http://stackoverflow.com/users/3694224/kerryz | |
#Questions or problems please reach me at hammadzz on github | |
#The serializers are timezone aware, they will check the timezone of the datetimefield object and serialize to a unix epoch timestamp (it is always in UTC). The magic piece that makes it work correctly is calendar.timegm() | |
#Add these serializers in serializers.py, the best practice is to make a new Django app called utils, and create a serializers.py file there which contains the code in this snippet. I have included an example using it below: | |
#utils/your-django-project/utils/serializers.py | |
from rest_framework import serializers | |
from django.core.exceptions import ValidationError | |
import datetime | |
import calendar | |
from pytz import utc # pip install pytz | |
class UnixEpochDateTimeField(serializers.DateTimeField): | |
def to_representation(self, value): | |
""" | |
to_representation method is responsible for turning the | |
Python object into a simple, serializable value. | |
Here: return epoch time for a datetime object or `None` | |
""" | |
return self.datetime_to_epoch(value) | |
def to_internal_value(self, value): | |
return self.epoch_to_datetime(value) | |
@staticmethod | |
def datetime_to_epoch(value): | |
try: | |
return int(calendar.timegm(value.utctimetuple())) | |
except (AttributeError, TypeError): | |
return None | |
@staticmethod | |
def epoch_to_datetime(value): | |
try: | |
return datetime.datetime.utcfromtimestamp(int(value)).replace(tzinfo=utc) | |
except (ValueError, TypeError): | |
raise ValidationError('%s is not a valid value' % value) | |
class UnixEpochDateField(serializers.DateField): | |
def to_representation(self, value): | |
return self.date_to_epoch(value) | |
def to_internal_value(self, value): | |
return self.epoch_to_date(value) | |
@staticmethod | |
def date_to_epoch(value): | |
try: | |
return int(calendar.timegm(value.timetuple())) | |
except (AttributeError, TypeError): | |
return None | |
@staticmethod | |
def epoch_to_date(value): | |
try: | |
return datetime.date.fromtimestamp(int(value)) | |
except (ValueError, TypeError): | |
raise ValidationError('%s is not a valid value' % value) | |
#Then lets say you want to serialize an example model with date_created in unix epoch, here is how you would do it: | |
#utils/your-django-project/example-app/serializers.py | |
from utils.serializers import UnixEpochDateTimeField | |
from .models import Example | |
class ExampleSerializer(serializers.ModelSerializer): | |
date_created = UnixEpochDateTimeField() | |
class Meta: | |
model = Example | |
fields = '__all__' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment