Skip to content

Instantly share code, notes, and snippets.

@harunurkst
Created April 1, 2019 05:16
Show Gist options
  • Save harunurkst/7181e5f05a8ec2dfaf88ef0d83f86b2d to your computer and use it in GitHub Desktop.
Save harunurkst/7181e5f05a8ec2dfaf88ef0d83f86b2d to your computer and use it in GitHub Desktop.
Custom serializer field to convert human readable date to timestamp
class TimeStampField(serializers.Field):
"""
A custom serializer field to convert human readable date (2019-04-01) to timestamp(1554094095)
"""
def to_representation(self, value):
"""
Convert timestamp to human readable time,
this function is called when api called to serialize data.
:param value: timestamp data
:return: 'YY-mm-dd' (i.e 2019-04-01)
"""
return datetime.datetime.fromtimestamp(value).date().isoformat()
def to_internal_value(self, data):
"""
convert human readable date to timestamp. this function is called when is_valid() method called.
:param data: Human readable date (2019-04-01)
:return: timestamp (1554094095)
"""
date_obj = datetime.datetime.strptime(data, '%Y-%m-%d').date() # string to date object
timestamp = time.mktime(date_obj.timetuple()) # date object to timestamp
return timestamp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment