Inserting a Python datetime.datetime object into MySQL

Scaraffe picture Scaraffe · Jul 16, 2009 · Viewed 223.8k times · Source

I have a date column in a MySQL table. I want to insert a datetime.datetime() object into this column. What should I be using in the execute statement?

I have tried:

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

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

I am getting an error as: "TypeError: not all arguments converted during string formatting" What should I use instead of %s?

Answer

g33kz0r picture g33kz0r · Dec 22, 2010

For a time field, use:

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

I think strftime also applies to datetime.