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

pythonserver side programmingprogramming更新于 2024/1/24 4:30:00

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

例如

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) 插入到您的表中。


相关文章