将datetime插入MySql db

Ala*_*ano 6 python mysql python-2.7

我有一个由strptime函数创建的日期时间值

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

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), ......)
Run Code Online (Sandbox Code Playgroud)

如何将此值插入db?

Mar*_*ers 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'),))
Run Code Online (Sandbox Code Playgroud)

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

仅使用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),))
Run Code Online (Sandbox Code Playgroud)