Django-rest-framework: No support for unix epoch timestamp for DateTimeField

Created on 17 Oct 2017  路  7Comments  路  Source: encode/django-rest-framework

Checklist

  • [x] I have verified that that issue exists against the master branch of Django REST framework.
  • [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
  • [x] This is not a usage question. (Those should be directed to the discussion group instead.)
  • [x] This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
  • [x] I have reduced the issue to the simplest possible case.
  • [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

Steps to reproduce

  • Create a serializer with DateTimeField
class DateSerializer(serializers.Serializer):

    date = fields.DateTimeField()
  • Pass UNIX epoch timestamp
    python shell >> a = DateSerializer(data={'date':'1508239944313'})
  • Validate the serializer by calling is_valid()

Expected Result

  • The serializer should validate the data

Actual Result

  • The serializer raises error upon validation

More Information

There should be a way to validate unix epoch timestamp by using DateTimeField by including an extra input_formats argument like input_formats=['epoch_timestamp']

Most helpful comment

@rpkilby @carltongibson Having something like TimestampField that serializes and deserializes the unix epoch timestamps is a very common use case, and providing support for it would be better than delegating it to user-land code.

I can raise a pull request if you are interested.

All 7 comments

I think this is just a limitation of the underlying strftime() and strptime() Behavior. There's no format for Unix Time timestamps there.

Instead you'll need to create a custom field using datetime.datetime.fromtimestamp() (or similar) in to_internal_value.

@carltongibson I can make a patch for DRF to support this input format in DateTimeField. We can use datetime.datetime.fromtimestamp() to parse the timestamp input in DateTimeField.
What do you think?

I think this is better in user-land code. A custom field would be simple enough.

I also agree. But seems like this format can also be included in the DateTimeField as this format is commonly used.

I'm -0 on this change to DateTimeField. If this were to be accepted, I'd rather see it added as a separate TimestampField or something similar.

please support epoch timestamp too!

@rpkilby @carltongibson Having something like TimestampField that serializes and deserializes the unix epoch timestamps is a very common use case, and providing support for it would be better than delegating it to user-land code.

I can raise a pull request if you are interested.

Was this page helpful?
0 / 5 - 0 ratings