How send Datetime as parameter in SQL command on Python?
<p>I have a sql command and just want to select some records with some conditions ( using python &amp; db is Postres): 
So, my query is:</p>

<pre><code> current_date= datetime.now()

  tt = yield self.db.execute(self.db.execute('SELECT "Id", "RubricId", "IsRubric"  
     FROM whis2011."CoockieUserInterests"
     'WHERE "UserId" = %s AND "Date" = %s '
     % (Id, current_date))

result=tt.fetchall()[0]
</code></pre>

<p>Problem: when I want to pass datetime to field "Date" I got error: </p>

<pre><code>syntax error at or near "00"
LINE 1: ...rests" WHERE "UserId" = 1 AND "Date" = 2016-10-05 00:22:07.3...
                                                         ^
</code></pre>

<p>All "Date" fields in db is like: 2016-09-25 00:00:00</p>

<p>Also, datatype of field "Date" in database is "timestamp without time zone".</p>

<p>it's my pool: </p>

<pre><code>    application.db = momoko.Pool(
    dsn='dbname=xxxx user=xxxxx password=xxxxx host=xxxx port=5432',
    size=1,
    ioloop=ioloop,
)
</code></pre>

<p>How I can select "Date" with format like this in my db? </p>

<p>You don't state what module you are using to connect to postgresql.  Let's assume for the interim that it is <code>psycopg2</code>. </p>

<p>In that case, you use the following to pass parameters to a query:</p>

<pre><code>current_date = datetime.now()

self.db.execute(
    'SELECT Id, RubricId, IsRubric '
    'FROM whis2011.CoockieUserInterests '
    'WHERE UserId = %s AND Date = %s',
     (Id, current_date))
</code></pre>

<p>Note we are <strong>not</strong> using the <code>%</code> interpolation operator on the sql string here.  Instead we are using <code>%s</code> to mark sql parameters and then passing them separately to <a href="https://www.python.org/dev/peps/pep-0249/#id15" rel="nofollow"><code>cursor.execute</code></a></p>

<p>If you are using a different package to connect to Postgres then it may mark parameters in a different manner.  Check the documentation or the modules <a href="https://www.python.org/dev/peps/pep-0249/#paramstyle" rel="nofollow"><code>paramstyle</code></a> for details.</p>

python postgresql datetime