Last active
December 5, 2022 10:21
-
-
Save maiksprenger/1b67662c489d7b710242190de9a992ff to your computer and use it in GitHub Desktop.
Django Rest Framework Unix Timestamp Field
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
class UnixTimestampField(serializers.FloatField): | |
""" | |
Stores Django datetimes as a Unix timestamp. | |
Thank you to Laur Ivan for the inspiration: | |
https://www.laurivan.com/timestamp-to-datetime-serializer-field-for-drf/ | |
""" | |
def to_internal_value(self, value): | |
""" | |
Convert a float of a Unix timestamp to an aware datetime | |
""" | |
# Convert given value to float, or fail | |
timestamp = super().to_internal_value(value) | |
# Convert to aware datetime | |
# If a timezone is given, fromtimestamp will always create a datetime for the | |
# same point in time. The only difference is the associated timezone. | |
# But that is slightly surprising, so to make it least surprising, we're | |
# returning an aware datetime based on UTC. | |
return datetime.fromtimestamp(timestamp, tz=timezone.utc) | |
def to_representation(self, value): | |
""" | |
Convert a datetime to a float of an Unix timestamp | |
Any timezone information is handled correctly by timestamp() | |
https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp | |
""" | |
return value.timestamp() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment