Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error datetime.date(2018, 6, 12) is not JSON serializable in Python

I am trying to use Flask-Ask and create an Alexa skill. I am getting issue while storing date and time into json

Below is the error

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.date(2018, 6, 12) is not JSON serializable

Below is the code snippet

@ask.intent("BookDateConfirmIntent")
def booking_confirmed(confirm_date):

    start_date = session['attributes']['startDate']
    data = {'services': '1234a', 'startDate': start_date, 'message': 'booking confirmed'}
    print json.dumps(data, indent=4, sort_keys=True, default=str)

The date being passed is like 2018-06-12

I read that we need to serialize this and I am not able to get it working correctly for the above code requirement. Someone please help. Thanks

like image 894
RaghuCK Avatar asked Apr 16 '26 18:04

RaghuCK


2 Answers

You can try type-casting the datetime object to string.

Change start_date to str(start_date).

like image 65
Nishant Jain Avatar answered Apr 19 '26 08:04

Nishant Jain


It doesn't matter whether you're taking present datetime or some in particular. What matters is the type(start_date) is datetime.date.

You can try something like this:

def myconverter(o):
    if isinstance(o, datetime.date):
        return "{}-{}-{}".format(o.year, o.month, o.day)

def booking_confirmed(confirm_date):

    start_date = myconverter(session['attributes']['startDate'])
    data = {'services': '1234a', 'startDate': start_date, 'message': 'booking confirmed'}
    print json.dumps(data, indent=4, sort_keys=True, default=str)
like image 21
Nikhil Wagh Avatar answered Apr 19 '26 08:04

Nikhil Wagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!