Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to serializ the date time object in python api
i have a api which will give json output and i am trying to save it as excel using xlsxwriter and i am getting this error

Object of type datetime is not JSON serializable





this is the api output

Quote:
"sub_start_date_end_date": [
{
"column_name": "country",
"column_value": "'USA'",
"display_text": "Country",
"end_date": "Fri, 03 Sep 2021 00:00:00 GMT",
"start_date": "Thu, 03 Sep 2020 00:00:00 GMT"
}
]


What I have tried:

Python
@final.route('/start_date-end_date', methods=['GET'])
def subscription_date():
    subscription_id = request.args.get('subscription_id')
    email = request.args.get('email')
    update_query = '''
            query
            '''
    result = db.session.execute(text(update_query), {'a':email})
    final = [dict(i) for i in result]
    excel = json.dumps(final)
    efile = json.load(excel, indent=4, cls=DateTimeEncoder)
    workbook = xlsxwriter.Workbook('myfile.xlsx')
    worksheet = workbook.add_worksheet()
    row = 0
    col = 0

    for key in efile:
        row += 1
        worksheet.write(row, col, key)
        worksheet.write(row, col + 1, efile[key])
        print(workbook)
        workbook.close()
    return{"sub_start_date_end_date":final}

class DateTimeEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.start_date, datetime.end_date)):
            return obj.isoformat()
Posted
Updated 20-Sep-20 22:43pm
v3

 
Share this answer
 
Generally, using of json.dumps with a custom converter.

The json.dumps method can accept an optional parameter called default which is expected to be a function. Every time JSON tries to convert a value it does not know how to convert it will call the function we passed to it. The function will receive the object in question, and it is expected to return the JSON representation of the object

Example:
Python
import json
import datetime
 
d = {
   'name' : 'Foo'
}
print(json.dumps(d))   # {"name": "Foo"}
 
d['date'] = datetime.datetime.now()
 
def myconverter(o):
    if isinstance(o, datetime.datetime):
        return o.__str__()
 
print(json.dumps(d, default = myconverter))    # {"date": "2016-04-08 11:43:36.309721", "name": "Foo"}


In your case, you can try a quick way like:
Python
excel = json.dumps(final, default=str)
By default, it converts everything it doesn't know to a string.

More reference to look: Python Serialize Datetime into JSON[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900