如何使用Python将日期存储和检索到MySQL数据库中?
要在MySQL数据库中插入日期,您的表中必须有一个类型为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,日期)。
当您使用选择查询从数据库中获取日期时,您需要使用诸如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')这将获取创建的日期并将其解析为datetime对象。
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿