如何使用Python在MySQL中插入日期对象?

要在MySQL数据库中插入日期,您的表中必须有一个类型为date或datetime的列。一旦有了它,就需要将日期转换为字符串格式,然后再将其插入数据库。为此,您可以使用datetime模块的strftime格式化功能。

例如

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

运行此命令将尝试在表中插入元组(id,日期)。