Psycopg2 的日期时间语法错误

Datetime syntax error with Psycopg2

我尝试在使用 Psycopg2 查询 Postgres 数据库时使用 Python 日期时间对象,但出现以下错误:

代码:

# createdat is a datetime variable I used before
print(type(createdat))

q = """
    select created_at
    from mytable t
    and t.created_at < %(createdat)s
    """ % {
        'createdat' : createdat
        }

read.execute(q)

Returns :

<type 'datetime.datetime'>

Traceback (most recent call last):
  File "import.py", line 346, in <module>
    read.execute(q)
  File "/usr/lib/python2.7/dist-packages/psycopg2/extras.py", line 120, in execute
    return super(DictCursor, self).execute(query, vars)
psycopg2.ProgrammingError: syntax error at or near "20"
LINE 6:         and created_at < 2015-05-05 20:22:22

有什么想法吗?提前致谢

q = """
select created_at
from mytable t
and t.created_at < %(createdat)s
"""

read.execute(q, {'createdat' : createdat})

试试这个方法,Psycopg2 会自己搞定一切