Inserting a Python datetime.datetime object into MySQL Inserting a Python datetime.datetime object into MySQL python python

Inserting a Python datetime.datetime object into MySQL


For a time field, use:

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

I think strftime also applies to datetime.


You are most likely getting the TypeError because you need quotes around the datecolumn value.

Try:

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

With regards to the format, I had success with the above command (which includes the milliseconds) and with:

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

Hope this helps.


Try using now.date() to get a Date object rather than a DateTime.

If that doesn't work, then converting that to a string should work:

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))