在 MS SQL Server 中使用 Python 时间增量结果并保存到时间类型时,数据类型无效。
start_time = (datetime.fromtimestamp(1553182159222 / 1e3))
end_time = (datetime.fromtimestamp(1553182159924/ 1e3))
run_time = end_time - start_time
返回结果:
0:00:00.702000
这是 timedelta 的正确数学,但在使用 run_time 变量作为 SQL Server 数据类型 TIME 的输入时出现错误。
最佳答案
timedelta
与 SQL Server 使用的字符串表示形式相同,因此只需将其作为字符串插入即可。
SQL:
CREATE TABLE test
(
timedelta time
)
Python:
start_time = (datetime.fromtimestamp(1553182159222 / 1e3))
end_time = (datetime.fromtimestamp(1553182159924/ 1e3))
run_time = end_time - start_time
cursor = cnxn.cursor()
cursor.execute("insert into test (timedelta) values (?)", str(run_time))
cnxn.commit()
cursor.execute("select timedelta from test")
row = cursor.fetchone()
while row:
print(str(row[0]))
row = cursor.fetchone()
输出:
00:00:00.702000
关于Python将timedelta类型转换为sql时间类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55580633/