Django REST Framework — Convert DateTime into timestamp without modifying any views or models

Jo-Yu Liao
3 min readApr 15, 2020

Python3, Django REST Framework 3.11.0

source: https://www.django-rest-framework.org

Suppose you have a model named User:

class User(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(default=timezone.now)

and you spend several hours on coding and finally create a new API of User to return the response like this:

{
"data": [
{
"id": 1,
"name": "John",
"created_at": "2020-04-15T03:32:49.106743Z"
}
]
}

Happily, you tell the front end developer you have finished the API. However, when you prepare to get off work, the front end developer come to your desk. He look at you, and ask you to convert DateTime into timestamp, oh, of course, for all of the APIs.

For example:

"created_at": "2020-04-15T03:32:49.106743Z"

should be:

 "created_at": 1586921569000

You look at your tens of thousands of APIs, and look back to the front end developer.

source: memegenerator.net

If you have this problem, don’t worry! Django REST Framework provide DATETIME_FORMAT which can help you to achieve your goal without modifying any views or models.

DATETIME_FORMAT

A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None, then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer.

What you need to do is to add the following code to settings.py:

REST_FRAMEWORK = {
'DATETIME_FORMAT': '%s',
}

Then all of the DateTime will be converted into timestamp like this:

"created_at": 1586921569

It’s easy, right? However the timestamp in Python is 10 digits unix, but in JavaScript is 13 digits unix. Therefore, the timestamp 1586921569 will not become 2020–04–15T03:32:49.106743Z, but be:

It should be 2020–04–15T03:32:49.106743Z
source: makeameme.org

Luckily, the way to convert 10 digits unix timestamp into 13 digits unix timestamp is to multiply it by 1000. So the final solution is:

REST_FRAMEWORK = {
'DATETIME_FORMAT': '%s000',
}

Congratulation! You convert all of the DateTime of APIs into 13 digits unix timestamp without modifying any views and models. :)

--

--