How to insert date object in MySQL using Python?


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 = 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.

Updated on: 04-Nov-2023

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements