将Python datetime.datetime对象插入MySQL

2024-04-20 12:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在MySQL表中有一个日期列。我想在这个列中插入一个datetime.datetime()对象。我应该在execute语句中使用什么?

我试过:

now = datetime.datetime(2009,5,5)

cursor.execute("INSERT INTO table
(name, id, datecolumn) VALUES (%s, %s
, %s)",("name", 4,now))

我得到一个错误为:"TypeError: not all arguments converted during string formatting" 我应该用什么代替%s


Tags: 对象nameidexecutedatetime错误mysqltable
3条回答

您很可能得到TypeError,因为在datecolumn值周围需要引号。

尝试:

now = datetime.datetime(2009, 5, 5)

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
               ("name", 4, now))

关于格式,我成功地使用了上述命令(包括毫秒)和:

now.strftime('%Y-%m-%d %H:%M:%S')

希望这有帮助。

对于时间字段,请使用:

import time    
time.strftime('%Y-%m-%d %H:%M:%S')

我认为strftime也适用于datetime。

尝试使用now.date()获取Date对象,而不是DateTime

如果这不起作用,那么将其转换为字符串应该起作用:

now = datetime.datetime(2009,5,5)
str_now = now.date().isoformat()
cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now))

相关问题 更多 >