如何使用 Python 将日期存储和检索到 MySQL 数据库中?
要在 MySQL 数据库中插入一个日期,需要在表中有一个 Type date 或 datetime 类型的列。有了它之后,在把它插入到数据库之前,需要把它转换成字符串格式。为此,你可以使用 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')这将获取 created date 并将其解析为 datetime 对象。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP