Psycopg2,基于日期/时间的选择

Wil*_*nes 3 python postgresql

我希望能够从数据库中的某个时间范围内进行选择。这就是我现在所拥有的,但它只选择所有行。

try:
    cur.execute("SELECT * from people_counter")
except:
    print "cannot select from node"
    sys.exit()

node_rows = cur.fetchall()
Run Code Online (Sandbox Code Playgroud)

数据库设置为三行,如下所示,

unit_id、时间戳、方向

文本,带时区的时间戳,文本

数据库是一个 Postgresql DB,使用 python 和 pyscopg2 作为包装器。

我只是不完全理解我如何将数据库中的某个列指定为日期/时间,以便仅从某个时间范围内选择行。

ber*_*nie 5

您可以在查询中指定值,

cur.execute("""SELECT * 
               FROM people_counter 
               WHERE time_stamp BETWEEN 
                   date '2015-06-01' and 
                   date '2015-06-30';""")
Run Code Online (Sandbox Code Playgroud)

作为参数

import datetime as dt
cur.execute("""SELECT * 
               FROM people_counter 
               WHERE time_stamp BETWEEN %s and %s;""", 
            (dt.date(2015,6,1), dt.date(2015,6,30)))
Run Code Online (Sandbox Code Playgroud)