Psycopg2的日期时间语法错误

时间:2015-09-04 11:19:07

标签: python postgresql psycopg2

我正在尝试使用Psycopg2在我的查询中使用Python datetime对象到Postgres数据库,但是我有以下错误:

代码:

# 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)

返回:

<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

有什么想法吗?提前致谢

1 个答案:

答案 0 :(得分:1)

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

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

尝试这种方式,Psycopg2将自行完成所有事情