How to overcome “datetime.datetime not JSON serializable”?

0 votes

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?

Jun 5 in Python by kartik
• 15,440 points
140 views

1 answer to this question.

0 votes

Hii @kartik,

The simple solution to over come "datetime not JSON serializable" problem.

enco = lambda obj: (
    obj.isoformat()
    if isinstance(obj, datetime.datetime)
    or isinstance(obj, datetime.date)
    else None
)
json.dumps({'date': datetime.datetime.now()}, default=enco)

Hope it work!

answered Jun 5 by Niroj
• 32,200 points

Related Questions In Python

0 votes
1 answer

Raw_input method is not working in python3. How to use it?

raw_input is not supported anymore in python3. ...READ MORE

answered May 4, 2018 in Python by aayushi
• 750 points
902 views
+1 vote
1 answer

how to convert json to csv or to store in sql

You can convert JSON data to csv ...READ MORE

answered Jul 2, 2018 in Python by Nietzsche's daemon
• 4,260 points
287 views
0 votes
1 answer

How to write "not equal" in python?

The keywords is and is not are ...READ MORE

answered Sep 17, 2018 in Python by SayantiniDeb
• 200 points
346 views
0 votes
1 answer

How can I convert JSON to CSV?

I am not sure this question is ...READ MORE

answered Oct 1, 2018 in Python by aryya
• 7,370 points
7,584 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,047 views
0 votes
0 answers
+4 votes
6 answers
0 votes
1 answer

How to convert a DictProxy object into JSON serializable dict?

Hello, Rather than using a private DictProxy method like _getvalue(), I'd ...READ MORE

answered Apr 15 in Python by Niroj
• 32,200 points
194 views
0 votes
1 answer

How to return None if Dictionary key is not available?

Hello @kartik, You should use the get() method from the dict class d ...READ MORE

answered Apr 13 in Python by Niroj
• 32,200 points
37 views