如何使用Python将日期对象插入MySQL数据库?
要将日期插入MySQL数据库,您需要在表中拥有一个类型为“date”或“datetime”的列。一旦您拥有了这个,您需要在将日期插入数据库之前将日期转换为字符串格式。为此,您可以使用datetime模块的strftime格式化函数。
阅读更多:Python 教程
例如
from datetime import datetime
now = datetime.now()
id = 1
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 假设您有一个名为“cursor”的游标,想要在其上执行此查询:
cursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date))
运行此程序将尝试将元组(id,date)插入到表中。