将Python datetime.datetime对象插入MySQL
我在一个MySQL表里有一个日期列。我想把一个 datetime.datetime()
对象插入到这个列里。我在执行语句的时候应该用什么呢?
我试过:
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
呢?
9 个回答
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))
52
你很可能遇到这个类型错误,是因为你在日期列的值周围需要加上引号。
试试这个:
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')
希望这对你有帮助。
244
对于时间字段,可以使用:
import time
time.strftime('%Y-%m-%d %H:%M:%S')
我觉得 strftime
也适用于 datetime
。