2

I am trying to return an outfit from m RDS database. The dte fields are all formatted in DATETIME which is causing me to get the following error:

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

How can I get around this?

heres my code:

import pymysql
import json
from rds import *

#rds settings
host  = rds_host
name = rds_name
password = rds_password
db_name = rds_db_name
port = rds_port

try:
    conn = pymysql.connect(host = host, user=name, passwd=password, db=db_name, connect_timeout=5)

except:
    raise Exception('Database Error: The server encountered an unexpected condition which prevented it from fulfilling the request.')


def handler(event, context):

    cur = conn.cursor(pymysql.cursors.DictCursor)
    #selects a user from the database
    query = "SELECT * FROM Outfits WHERE outfit_id = '" + event['outfitId'] + "' LIMIT 1"
    #runs the SQL query
    try:
        cur.execute(query)
    except:
        raise Exception('Internal Error: The server encountered an unexpected condition which prevented it from fulfilling the request.')

    #stores the downloaded record into the user variable
    rows = cur.fetchone()
    return result
user3024827
  • 1,228
  • 4
  • 18
  • 36
  • 1
    I don't think this is a duplicate of the question given above. The OP has no control over _how_ AWS converts the MySQL query to Json, as it is done outside of the Lambda function by AWS itself. As a result, the fix needs to be done on the query results themselves rather than modifying the JSON encoder (as there is no guarentee how AWS converts the results to a JSON string). – Lee Winder Sep 14 '16 at 09:49

2 Answers2

5

Haven't used AWS Lambda but this issue is python specific. datetime.datetime objects cannot be JSON serialized, you need to convert them to strings before JOSN serializing. You can use .strftime() to convert your datetime.datetime objects to strings.

Muhammad Tahir
  • 5,006
  • 1
  • 19
  • 36
0

Can you not store the datetime in a different format? looks like the response from querying the database is JSON format, storing the date as a string would be much more efficient surely?

Tom
  • 343
  • 1
  • 13
  • But i then need to query to database, getting results ordered by date and therefore need the datetime format to do this – user3024827 Feb 23 '16 at 13:08