如何使用Python将日期存储和检索到MySQL数据库中?
要在MySQL数据库中插入日期,您需要在表中拥有一个date或datetime类型的列。一旦您拥有它,您需要在插入到数据库之前将日期转换为字符串格式。为此,您可以使用datetime模块的strftime格式化函数。
阅读更多:MySQL 教程
示例
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)插入到您的表中。
从数据库中使用select查询获取日期时,您需要使用strptime等函数将其解析回datetime对象。
示例
from datetime import datetime
# 假设您有一个名为cursor的光标,您想要在其上执行此查询:
cursor.execute('select id, date_created from table where id=1')
# 如果您插入了上面的行,则可以按如下方式获取它
id, date_str = cursor.fetchone()
# 日期以我们发送的格式作为字符串返回。因此,使用strptime进行解析
created_date = datetime.strptime(date_created, '%Y-%m-%d %H:%M:%S')
这将获取创建的日期并将其解析为datetime对象。
极客教程