在Python中插入一个Python datetime.datetime对象

我有一个MySQL表中的date列。 我想插入一个datetime.datetime()对象到这个列。 我应该在执行声明中使用什么?

我努力了:

 now = datetime.datetime(2009,5,5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s , %s)",("name", 4,now)) 

我得到一个错误: "TypeError: not all arguments converted during string formatting"我应该用什么,而不是%s

对于时间字段,请使用:

 import time time.strftime('%Y-%m-%d %H:%M:%S') 

我认为strftime也适用于datetime。

您最有可能得到TypeError,因为您需要引用date列的值。

尝试:

 now = datetime.datetime(2009, 5, 5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')", ("name", 4, now)) 

关于格式,我已经成功地使用了上面的命令(包括毫秒)和:

 now.strftime('%Y-%m-%d %H:%M:%S') 

希望这可以帮助。

尝试使用now.date()来获取Date对象而不是DateTime

如果这不起作用,那么将其转换为string应该工作:

 now = datetime.datetime(2009,5,5) str_now = now.date().isoformat() cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now)) 

你连接到哪个数据库? 我知道Oracle对date格式很挑剔,并且喜欢ISO 8601格式。

**注意:哎呀,我刚刚读到你在MySQL上。 只需格式化date,并将其作为单独的直接SQL调用来testing。

在Python中,你可以得到ISO的date

 now.isoformat() 

例如,Oracle喜欢像

 insert into x values(99, '31-may-09'); 

根据您的数据库,如果是Oracle,您可能需要TO_DATE:

 insert into x values(99, to_date('2009/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam')); 

TO_DATE的一般用法是:

 TO_DATE(<string>, '<format>') 

如果使用其他数据库(我看到光标,并认为甲骨文;我可能是错的),然后检查他们的date格式工具。 对于MySQL是DATE_FORMAT()和SQL Server是CONVERT。

同样使用像SQLAlchemy这样的工具将会消除这些差异,让您的生活变得轻松。

如果你只是使用python datetime.date(而不是一个完整的datetime.datetime)只需要将date转换为一个string。 这非常简单,适用于我(mysql,python 2.7,Ubuntu)。 published_date列是一个MySQLdate字段,pythonvariables的发布date是datetime.date。

 # make the record for the passed link info sql_stmt = "INSERT INTO snippet_links (" + \ "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \ "VALUES(%s, %s, %s, %s, %s, %s, %s) ;" sql_data = ( title, link, str(publish_date), \ author, posted_by, \ str(coco_id), str(link_id) ) try: dbc.execute(sql_stmt, sql_data ) except Exception, e: ...