Question

I would not call myself a newbie, but I am not terribly conversant with programming. Any help would be appreciated. I have this project that is almost done. Figured out lots of stuff, but this issue has me at a loss.

Is there a simple way to insert an acceptable date value in a postgresql query from:

start_date = raw_input('Start date: ')
end_date = raw_input('End date: ')

I want the variables above to work in the following.

WHERE (gltx.post_date > start_date AND gltx.post_date < end_date )

'YYYY-MM-DD' format works in the SELECT Query of the postgresql database through python triple quoted cursor.execute.

The postgresql column(post.date) is date format.

here is the header for the python script.

#!/usr/bin/python
import psycopg2 as dbapi2
import psycopg2.extras
import sys
import csv

For now I have been altering the query for different periods of time.

Also is there an easy way format the date returned as YYYYMMDD. Perhaps a filter that replaced dashes or hyphens with nothing. I could use that for phone numbers also.

Was it helpful?

Solution

If you are going to execute this SELECT inside a Python script, you should not be placing strings straight into your database query - else you run the risk of SQL injections. See the psycopg2 docs - the problem with query parameters.

Instead you need to use placeholders and place all your string arguments into an iterable (usually a tuple) which is passed as the second argument to cursor.execute(). Again see the docs -passing parameters to sql queries.

So you would create a cursor object, and call the execute() method passing the query string as the first argument and a tuple containing the two dates as the second. Eg

query = "SELECT to_char(gltx.post_date, 'YYYYMMDD') FROM gltx WHERE (gltx.post_date > %s AND gltx.post_date < %s)"
args = (start_date, end_date)
cursor.execute(query, args)

To format the date in Python space, you can use the strftime() method on a date object. You should probably be working with datetime objects not strings anyway, if you want to do anything more than print the output.

You also probably want to validate that the date entered into the raw_input() is a valid date too.

OTHER TIPS

Use the cursor.execute method's parameter substitution

import psycopg2

query = """
    select to_char(gltx.post_date, 'YYYYMMDD') as post_date
    from gltx
    where gltx.post_date > %s AND gltx.post_date < %s
;"""

start_date = '2014-02-17'
end_date = '2014-03-04'

conn = psycopg2.connect("dbname=cpn")
cur = conn.cursor()
cur.execute(query, (start_date, end_date))
rs = cur.fetchall()
conn.close()
print rs
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top