我在MySQL表中有一个date列。我想在这个列中插入一个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
发布于 2010-12-22 19:56:18
对于时间字段,请使用:
import time    
time.strftime('%Y-%m-%d %H:%M:%S')我认为strftime也适用于datetime。
发布于 2012-08-30 14:59:51
您最有可能获得TypeError,因为您需要用引号将日期列值括起来。
尝试:
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')希望这能有所帮助。
发布于 2009-07-16 09:39:15
尝试使用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))https://stackoverflow.com/questions/1136437
复制相似问题