How to insert date object in MySQL using Python?

PythonServer Side ProgrammingProgramming

To insert a date in a MySQL database, you need to have a column of Type date or datetime in your table. Once you have that, you'll need to convert your date in a string format before inserting it to your database. To do this, you can use the datetime module's strftime formatting function.

For example

from datetime import datetime
now =
id = 1
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# Assuming you have a cursor named cursor you want to execute this query on:
cursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date))

Running this will try to insert the tuple (id, date) in your table.

Published on 08-Jan-2018 10:25:23