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
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.