【问题标题】:How do I pass a date to MySQLdb in Python?如何在 Python 中将日期传递给 MySQLdb?
【发布时间】:2016-04-07 07:26:28
【问题描述】:

我正在尝试使用日期作为变量进行相当简单的 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 |
+------+------+------------+

有什么想法吗?谢谢。

【问题讨论】:

    标签: python datetime mysql-python sqldatatypes


    【解决方案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,))
    

    【讨论】:

    • 好吧,我必须承认,这不是错字,我的 python 非常有限。感谢你们两个@Limar 和@Rogalski,就像一个魅力。有趣的是这个aujourdhui = str('%s') %(today) 没有引起任何错误。
    【解决方案2】:

    您的查询行基本上是:

    cur.execute('QUERY') % (today)
    

    它将% 运算符应用于cur.execute('QUERY') 返回值,它是整数。因此您收到TypeError - long % datetime 未定义为 long 类型,您实际上想做string % something 操作。

    要执行字符串格式化,您必须将 % 运算符移动到 cur.execute 参数 - 将其称为 cur.execute('QUERY' % today)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多