将datetime插入MySql db

时间:2013-05-03 12:38:21

标签: python mysql python-2.7

我有一个由strptime函数

创建的日期时间值
import MySQLdb
a = time.strptime('my date', "%b %d %Y %H:%M")

MySql db中有一个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), ......)

如何将此值插入db?

1 个答案:

答案 0 :(得分:9)

您现在正在传递一个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),))
相关问题