解决python写入mysql中datetime类型遇到的问题
刚开始使用python,还不太熟练,遇到一个datetime数据类型的问题:

在mysql数据库中,有一个datetime类型的字段用于存储记录的日期时间值。python程序中有对应的一个datetime变量dt。
现在需要往mysql数据库中添加记录,每次添加时,将datetime型变量dt写入mysql数据库tablename表中exTime字段里。
问题是,怎么写?在调试时,它总是无法写入。
[En]
Question, how to write? When debugging, it is always unable to write.
运行环境:windows10 python 3.6 mysql5.6.38
运行结果提示:
[En]
The running result prompts:
Process finished with exit code 0
——看我写的程序————-
import datetime
import pymysql.cursors
conn = pymysql.connect(host=’127.0.0.1′,
port=3306,
user=’root’,
password=”,
db=’test’,
charset=’utf8′,
cursorclass=pymysql.cursors.DictCursor)
中间略去dt赋值部分…
print(dt.strftime(‘%Y-%m-%d %H:%M:%S’))
运行结果是 2001-1-2 11:00:00
sql_insert=sql_insert=”INSERT into tablename(exTime) values(%s)” %(dt.strftime(“%Y-%m-%d %H:%M:%S”))
如果此处写成sql_insert=sql_insert=”INSERT into tablename(exTime) values(‘2001-1-2 11:00:00’)” 则可以运行
try:
with conn.cursor() as csor1:
csor1.execute(sql_insert)
conn.commit()
csor1.close()
except Exception as e:
错误回滚
conn.rollback()
finally:
conn.close()
———————————–
后来在网上查了一下,mysql中datetime类型字段,赋值时最好用str_to_date函数转化成mysql的datetime类型
因此,上述方案已更改:
[En]
Therefore, the above program has been changed:
sql_insert=sql_insert=”INSERT into tablename(exTime) values(str_to_date(\’%s\’,’%%Y-%%m-%%d %%H:%%i:%%s’))” %(dt.strftime(“%Y-%m-%d %H:%M:%S”))
再跑一次,传球!
[En]
Rerun, pass!
以上这篇解决python写入mysql中datetime类型遇到的问题就是小编分享给大家的全部内容了
Original: https://www.cnblogs.com/amengduo/p/9586234.html
Author: 刘小子
Title: 解决python写入mysql中datetime类型遇到的问题
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/7404/
转载文章受原作者版权保护。转载请注明原作者出处!