登录
首页 >  数据库 >  MySQL

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

来源:tutorialspoint

时间:2023-09-06 18:25:41 209浏览 收藏

小伙伴们对数据库编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《如何使用 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')

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

今天带大家了解了的相关知识,希望对你有所帮助;关于数据库的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:tutorialspoint 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>