python - 将日期时间插入 MySql 数据库

标签 python mysql python-2.7

我有一个由 strptime 函数生成的日期时间值

import MySQLdb
a = time.strptime('my date', "%b %d %Y %H:%M")

MySql 数据库中有一列类型为 DATETIME。当我尝试将此值插入 db 时,很明显,我得到了

的错误
mysql_exceptions.OperationalError: (1305, 'FUNCTION time.struct_time does not exist')

INSERT INTO myTable(Date......) VALUES(time.struct_time(tm_year=2222, tm_mon=4, tm_mday=1, tm_hour=1, tm_min=2, tm_sec=4, tm_wday=1, tm_yday=118, tm_isdst=-1), ......)

如何将这个值插入数据库?

最佳答案

您现在传递的是 time.struct_time 对象,MySQL 对此一无所知。您需要将时间戳格式化为 MySQL 可以理解的格式。不幸的是,MySQLdb 库不会为您做这件事。

使用 datetime 模块最简单,但您也可以使用 time 模块来做到这一点:

import datetime

a = datetime.datetime.strptime('my date', "%b %d %Y %H:%M")

cursor.execute('INSERT INTO myTable (Date) VALUES(%s)', (a.strftime('%Y-%m-%d %H:%M:%S'),))

.strftime() 方法调用 datetime.datetime 对象以 MySQL 接受的方式格式化信息。

只用 time 模块完成同样的任务:

import time

a = time.strptime('my date', "%b %d %Y %H:%M")

cursor.execute('INSERT INTO myTable (Date) VALUES(%s)', (time.strftime('%Y-%m-%d %H:%M:%S', a),))

关于python - 将日期时间插入 MySql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16359143/

相关文章:

python - 当我在 pandas 中使用 diff(periods=1) 计算时间间隔时出现错误

python - SQLAlchemy 连接在 AWS MySQL RDS 重启时挂起并进行故障转移

mysql - SQL:按一列中相同值的数量排序,无需聚合/收缩

python - 如何在sql命令中使用python变量

python - 如何从二进制骨架化图像中找到分支点

python - 通过相关对象权限的 Django 权限

python - Altair 数据聚合

Python re.findall() 和优先级

php - Laravel leftJoin 现在显示结果

python-2.7 - 在 pygame.mixer 中改变音量(几乎)没有效果