Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overcome "datetime.datetime not JSON serializable"?

Tags:

python

json

I have a basic dict as follows:

sample = {} sample['title'] = "String" sample['somedate'] = somedatetimehere 

When I try to do jsonify(sample) I get:

TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable 

What can I do such that my dictionary sample can overcome the error above?

Note: Though it may not be relevant, the dictionaries are generated from the retrieval of records out of mongodb where when I print out str(sample['somedate']), the output is 2012-08-08 21:46:24.862000.

like image 472
Rolando Avatar asked Aug 09 '12 02:08

Rolando


People also ask

How do I fix the object of type datetime is not JSON serializable?

The Python "TypeError: Object of type datetime is not JSON serializable" occurs when we try to convert a datetime object to a JSON string. To solve the error, set the default keyword argument to str in your call to the json. dumps() method.

How do I make datetime JSON serializable in Python?

Serialize datetime by converting it into String We need to set the default parameter of a json. dump() or json. dumps() to str like this json. dumps(obj, default=str) .

Why is a set not JSON serializable?

The Python "TypeError: Object of type set is not JSON serializable" occurs when we try to convert a set object to a JSON string. To solve the error, convert the set to a list before serializing it to JSON, e.g. json. dumps(list(my_set)) . Here is an example of how the error occurs.

How do I convert a datetime to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.


2 Answers

Building on other answers, a simple solution based on a specific serializer that just converts datetime.datetime and datetime.date objects to strings.

from datetime import date, datetime  def json_serial(obj):     """JSON serializer for objects not serializable by default json code"""      if isinstance(obj, (datetime, date)):         return obj.isoformat()     raise TypeError ("Type %s not serializable" % type(obj)) 

As seen, the code just checks to find out if object is of class datetime.datetime or datetime.date, and then uses .isoformat() to produce a serialized version of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily decoded by JavaScript). If more complex serialized representations are sought, other code could be used instead of str() (see other answers to this question for examples). The code ends by raising an exception, to deal with the case it is called with a non-serializable type.

This json_serial function can be used as follows:

from datetime import datetime from json import dumps  print dumps(datetime.now(), default=json_serial) 

The details about how the default parameter to json.dumps works can be found in Section Basic Usage of the json module documentation.

like image 31
jgbarah Avatar answered Oct 27 '22 04:10

jgbarah


My quick & dirty JSON dump that eats dates and everything:

json.dumps(my_dictionary, indent=4, sort_keys=True, default=str) 

default is a function applied to objects that aren't serializable.
In this case it's str, so it just converts everything it doesn't know to strings. Which is great for serialization but not so great when deserializing (hence the "quick & dirty") as anything might have been string-ified without warning, e.g. a function or numpy array.

like image 58
jjmontes Avatar answered Oct 27 '22 05:10

jjmontes