首页 > 解决方案 > 如何标点使用 FROM_UNIXTIME 的 INSERT 语句

问题描述

Python环境中,我有以下变量:

post_time_ms="1581546697000"

这是一个以毫秒为单位的 Unix 风格的时间。

在我的表中,“created_date_time”被定义为一个日期时间列。

我正在尝试使用以下形式的 INSERT 语句:

sql_insert_query = "INSERT INTO myTable (id_string, text,
 created_date_time) VALUES ('identifier', 'text_content',
 FROM_UNIXTIME('post_time/1000')"

我不知道我应该如何标点它。如果我运行如上所示的查询,我会得到:

"Failed to insert record 1292 (22007): Truncated incorrect DECIMAL value: 'post_time/1000'

我已经尝试了所有我能想到的单引号/无引号的变体,但我总是会出错。

例如,如果我这样做:

sql_insert_query = "INSERT INTO myTable (id_string, text,
 created_date_time) VALUES ('identifier', 'text_content',
 FROM_UNIXTIME('post_time'/1000)"

我得到:

Failed to insert record 1292 (22007): Truncated incorrect DOUBLE value: 'post_time'

我已经尝试将 Unix 风格的“1581546697000”值转换如下:

post_time_mysql = datetime.fromtimestamp(int(post_time)/1000)

接着:

sql_insert_query = "INSERT INTO myTable (id_string, text,
 created_date_time) VALUES ('identifier', 'text_content',
 'post_time_mysql')"

即使

print(post_time_mysql)

输出“2020-02-14 09:25:28”,

对于上述查询,我​​仍然收到此错误:

Failed to insert record 1292 (22007): Incorrect datetime value: 'post_time_mysql' for column `myDatabase`.`myTable`.`created_date_time` at row 1

有什么想法/建议吗?

==========

我的解决方法是执行以下操作:

sql_insert_query = "INSERT INTO myTable (id_string, text, created_date_time) VALUES (%s, %s, %s)"

sql_insert_data = (identifier, text_content, post_time_mysql)

cursor.execute(sql_insert_query, sql_insert_data)

但是我仍然不明白如何使用一个查询语句成功地做到这一点 - 如果可能的话。

标签: mysqldatetimepython

解决方案


推荐阅读