Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying by current time (postgres, psycopg2, python)

I'm making a Flask application that queries a postgreSQL database using psycopg2. The database has a column timestamps in the format YYYY-MM-DD HH:MI:SS. I want to print ONLY the results that match the current time up to the minute (the moment I query the db). I think what I'm looking for is a dynamic query.

For example, here I want to print the number of users CURRENTLY active.

def userCount(conn):
    cur = conn.cursor()
    cur.execute("SELECT * from user_list WHERE timestamps = ?")
    print 'Users currently active: ' + str(len(cur.fetchall()))

I've tried placing several different things where the question mark is above, including a variable dt defined using python's datetime module. Nothing has worked--I either end up getting a count of all the users in the database, or an error that the column does not exist.

To reiterate, I know how to specify date-time parameters but what I need is the CURRENT date-time. What's the proper way to do this?

like image 294
Sarah Avatar asked Jan 18 '26 09:01

Sarah


1 Answers

 intervalInSecs = 30;

 def userCount(conn):
        cur = conn.cursor()
        cur.execute("SELECT * from user_list WHERE timestamps > (current_timestamp - make_interval(secs := %s))", [intervalInSecs])
        print 'Users currently active: ' + str(len(cur.fetchall()))
like image 60
Abelisto Avatar answered Jan 20 '26 23:01

Abelisto