Python字符串日期存到mysql_如何使用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对象。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值