AWS Lambda TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000)不能被序列化为JSON。
AWS Lambda TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000)不能被序列化为JSON。
这个问题已经有答案了:
我试图从我的RDS数据库返回一套衣服。所有的dte字段都是DATETIME格式,这导致我得到以下错误:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
我该如何解决这个问题?
这是我的代码:
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
admin 更改状态以发布 2023年5月25日
没有使用过AWS Lambda,但这个问题是与python有关的。 datetime.datetime
对象无法被JSON序列化,需要在JSON序列化之前将它们转换为字符串。您可以使用.strftime()
将datetime.datetime
对象转换为字符串。