Python 使用json\u populate\u记录向数据库插入日期时间
如何使用Python 使用json\u populate\u记录向数据库插入日期时间,python,json,postgresql,Python,Json,Postgresql,如何使用json\u populate\u record将python的datetime插入时间戳列 我尝试了[建议][1]。但当我使用json\u populate\u record时,它对我不起作用: def add_trade(self, order_sell_id: UUID, execution_time: datetime): trade = { "order_sell_id": order_sell_id, "execution_time":
json\u populate\u record
将python的datetime
插入时间戳列
我尝试了[建议][1]。但当我使用json\u populate\u record
时,它对我不起作用:
def add_trade(self, order_sell_id: UUID, execution_time: datetime):
trade = {
"order_sell_id": order_sell_id,
"execution_time": "TIMESTAMP " + str(execution_time)
}
try:
order_sql = (
f"INSERT INTO \"trade\"(order_sell_id, execution_time) "
f" SELECT order_sell_id, execution_time"
f" FROM "
f"json_populate_record(NULL::\"trade\", '{json.dumps(trade)}');")
result = self.database.query(order_sql)
except pg.IntegrityError as e:
pass
对于上述代码,我有一个例外:
pg.DataError: ERROR: invalid input syntax for type timestamp: "TIMESTAMP 2018-06-15 16:14:36"
我试着插入datetime
,只是在dict中添加了:
"execution_time": execution_time
得到:
pg.DataError: ERROR: date/time field value out of range: "1529069127000"
只需使用str()
:
或者使用strftime()
格式化日期时间:
"execution_time": str(execution_time)
"execution_time": execution_time.strftime("%Y-%m-%d %H:%M:%S")