如何在Python中将日期传递给MySQLdb?

时间:2016-01-03 15:44:05

标签: python datetime mysql-python sqldatatypes

我正在尝试用日期作为变量做一个相当简单的SELECT。但我总是收到数据类型错误:

today = datetime.datetime.date(datetime.datetime.now())
cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "%s"') %(today)

它抛出异常:

moncal.py:61: Warning: Incorrect date value: '%s' for column 'thedate' at row 1
cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "%s"') %(today)
(...)
TypeError: unsupported operand type(s) for %: 'long' and 'datetime.date'`

我的数据库有数据:

mysql> select * from agenda
    -> ;
+------+------+------------+
| id_t | id_c | thedate    |
+------+------+------------+
|    3 |    5 | 2015-12-12 |
|    1 |    6 | 2015-12-24 |
+------+------+------------+

有什么想法吗?感谢。

2 个答案:

答案 0 :(得分:1)

看起来是一个简单的错字。字符串格式的Python表达式应该类似于'%s'%variable,而不是('%s') % variable

具体来说,使用

cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "%s"' % today)

或者考虑使用推荐的语法(请参阅https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute)和?占位符:

cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "?"',(today,))

答案 1 :(得分:1)

您的查询行基本上是:

puts (if a == 1 then "Yes!" else "No!" end)

它将cur.execute('QUERY') % (today) 运算符应用于%返回值,即整数。因此,您收到cur.execute('QUERY') - TypeError未定义为长类型,并且您实际上希望执行long % datetime操作。

要执行字符串格式设置,您必须将string % something运算符移至%参数 - 将其称为cur.execute