
要在 MySQL 数据库中插入日期,您的表中需要有一列类型为日期或日期时间的列。完成后,您需要将日期转换为字符串格式,然后再将其插入数据库。为此,您可以使用 datetime 模块的 strftime 格式化函数。
示例
from datetime import datetimenow = datetime.now()id = 1formatted_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,date)插入到您的表中。
当您使用select查询从数据库中获取日期时,您需要使用strptime等函数将其解析回datetime对象。
如知AI笔记
如知笔记——支持markdown的在线笔记,支持ai智能写作、AI搜索,支持DeepseekR1满血大模型
27 查看详情
示例
from datetime import datetime# Assuming you have a cursor named cursor you want to execute this query on:cursor.execute('select id, date_created from table where id=1')# if you inserted the row above, you can get it back like thisid, date_str = cursor.fetchone()# date is returned as a string in format we sent it as. So parse it using strptimecreated_date = datetime.strptime(date_created, '%Y-%m-%d %H:%M:%S')
这将获取创建日期并将其解析为日期时间对象。
立即学习“Python免费学习笔记(深入)”;
以上就是如何使用 Python 在 MySQL 数据库中存储和检索日期?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/225907.html
微信扫一扫
支付宝扫一扫