AWS Lambda TypeError:datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) 不是 JSON 可序列化的 [重复]
Posted
技术标签:
【中文标题】AWS Lambda TypeError:datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) 不是 JSON 可序列化的 [重复]【英文标题】:AWS Lmbda TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable [duplicate] 【发布时间】:2016-06-05 02:17:27 【问题描述】:我正在尝试从 m 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
【问题讨论】:
我认为这不是上面给出的问题的重复。 OP 无法控制 如何 AWS 将 MySQL 查询转换为 Json,因为它是由 AWS 本身在 Lambda 函数之外完成的。因此,需要对查询结果本身进行修复,而不是修改 JSON 编码器(因为无法保证 AWS 如何将结果转换为 JSON 字符串)。 【参考方案1】:没有使用过 AWS Lambda,但这个问题是特定于 python 的。 datetime.datetime
对象不能被 JSON 序列化,你需要在 JOSN 序列化之前将它们转换为字符串。您可以使用.strftime()
将您的datetime.datetime
对象转换为字符串。
【讨论】:
【参考方案2】:不能以不同的格式存储日期时间吗?看起来查询数据库的响应是 JSON 格式,将日期存储为字符串肯定会更有效吗?
【讨论】:
但是我需要查询数据库,获取按日期排序的结果,因此需要日期时间格式来执行此操作以上是关于AWS Lambda TypeError:datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) 不是 JSON 可序列化的 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
node-lambda - TypeError:处理程序不是函数
TypeError: 'int' 对象在使用 reduce 和 lambda 时不可调用