简体   繁体   中英

Datetime syntax error with Psycopg2

I'm trying to use Python datetime objects in my queries to a Postgres database using Psycopg2, but I have the following error :

The code :

# 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

Any idea ? Thanks in advance

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

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

Try this way, Psycopg2 will do everything by itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM