【问题标题】:How to retrieve rows using datetime (python & mysql)如何使用日期时间检索行(python 和 mysql)
【发布时间】:2014-06-07 19:49:19
【问题描述】:

这是我的代码:

now  = datetime.datetime.now().replace(microsecond=0)
curs.execute("SELECT name, msgDate,  FROM test where msgDate=%s",(now))

我收到了这些消息:

File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 220, in _process_params
  res = list(map(to_mysql,res))
TypeError: 'datetime.datetime' object is not iterable
During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\projectse\Email\src\a.py", line 65, in <module>
    curs.execute("SELECT name, msgDate FROM messages where msgDate=%s",(now))
  File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 300, in execute
    stmt = operation % self._process_params(params)
  File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 225, in _process_params
  "Failed processing format-parameters; %s" % e)
  mysql.connector.errors.ProgrammingError: -1: Failed processing format-parameters; 
  'datetime.datetime' object is not iterable

有什么建议吗?

【问题讨论】:

    标签: python mysql database datetime


    【解决方案1】:

    我认为你应该替换:

    curs.execute("SELECT name, msgDate, FROM test where msgDate=%s",(now))
    

    与:

    curs.execute("SELECT name, msgDate, FROM test where msgDate=%s",%(now))
    

    并将其用于您的时间变量:

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

    如果您想知道为什么会出现问题,请尝试查看 now = str(datetime.datetime.now().replace(microsecond=0)) 在 python 解释器中的样子。

    【讨论】:

    • 好的,我想我实际上看到了你的问题不是。 datetime.datetime.now() 现在看起来像 datetime.datetime(2014, 6, 7, 19, 36, 5, 977972),我想它不能很好地与 SQL 日期配合使用。
    【解决方案2】:
       now = datetime.datetime(2012, 2, 23, 0, 0)
       now.strftime('%m/%d/%Y')
    
    
        curs.execute("SELECT name, msgDate,  FROM test where msgDate=:now",dict(now=str(now))
    
        please try converting date to string format and execute
    

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 1970-01-01
      • 2020-03-20
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 2019-04-25
      • 2022-01-24
      相关资源
      最近更新 更多