如何使用 Python 在 MySQL 数据库中存储和检索日期?

PHPz
发布: 2023-09-14 22:37:02
转载
487 人浏览过

如何使用 Python 在 MySQL 数据库中存储和检索日期?

要在 MySQL 数据库中插入日期,您的表中需要有一列类型为日期或日期时间的列。完成后,您需要将日期转换为字符串格式,然后再将其插入数据库。为此,您可以使用 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,date)插入到您的表中。

当您使用select查询从数据库中获取日期时,您需要使用strptime等函数将其解析回datetime对象。

示例

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 this
id, date_str = cursor.fetchone()
# date is returned as a string in format we sent it as. So parse it using strptime
created_date = datetime.strptime(date_created, '%Y-%m-%d %H:%M:%S')
登录后复制

这将获取创建日期并将其解析为日期时间对象。

以上是如何使用 Python 在 MySQL 数据库中存储和检索日期?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!