Image 14282+ users

Serialising 'datetime' objects in Python

Serialising 'datetime' objects in Python

22/08/18   4 minutes read     908 Naren Allam


Eventhough there are many similarities between python dictionary and json, due to it’s superiority and rich data types, some objects in python are not serializable to json by default.

For example datetime.datetime objects.

Here is how we can resolve this issue

Always remember to convert ‘datetime’ to ‘toJson’ format which conforms to ISO 8601 from UI / client side and transmit it to API’s.

For e.g "2018-08-15T18:25:43. 537323Z"

It is always a good practice to convert datetime values received in POST requests from ISO string format to python datetime objects. Because python datetime objects are easy to be queried and directly be inserted into any databases like MongoDB, MySQL, sqlite3 etc.., as datetime fields.

Below code will help you to resolve that problem

                      import dateutil.parser            
data = request.json
data['some_datetime_field'] = dateutil.parser.parse(data['some_datetime_field'])

Note:- If throws error, try to run the command ‘pip install python-dateutil'

It will convert “2018-08-15T18:25:43. 537323Z” to datetime.datetime(2018, 8, 15, 18, 25, 43, 537323).

In same way, while sending response in json format convert datetime objects to ISO format by using .isoformat( ) as shown in the below example.

                      resp_data = {"some_date_field": datetime.datetime(2018, 8, 15, 18, 25, 43, 537323)}

# To convert from datetime.datetime(2018, 8, 15, 18, 25, 43, 537323) to “2018-08-15T18:25:43. 537323Z”
resp = {"some_date_field": resp_data{"some_date_field"].isoformat()}