简体   繁体   English

Psycopg2-查询postgreSQL数据库cur.execute的最后24小时

[英]Psycopg2 - Query last 24hrs of postgreSQL database cur.execute

I am having difficulty querying all data from a table during the last 24hrs and it is difficult to say if its a postgres error on my part of python since im a beginner 我在过去的24小时内很难查询表中的所有数据,而且由于我是初学者,所以很难说这是否是我本人的python postgres错误

I see the "publishedAt" field, returns a datetime.datetime value. 我看到“ publishedAt”字段,返回一个datetime.datetime值。

# print out columns names
cur.execute(
    """
    SELECT *
    FROM "table"
    LIMIT 1
    """
)

# print out columns names
colnames = [desc[0] for desc in cur.description]
print(colnames)

# print out col values
rows = cur.fetchall()
print(rows)

['id', 'publishedAt', ......]
[['5a086f56-d080-40c0-b6fc-ee78b08aec3d', datetime.datetime(2018, 11, 11, 
15, 39, 58, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), .....]

However, 然而,

cur.execute(
    """
    SELECT * 
    FROM "table"
    WHERE publishedAt BETWEEN %s and %s;""", 
    (dt.datetime.now() - dt.timedelta(days=1))
)    

results in: 结果是:

TypeError: 'datetime.datetime' object does not support indexing

is it possible to use datetime library in psycopg2 queries? 是否可以在psycopg2查询中使用日期时间库?

you want to pass a tuple into cur.execute() , you're passing a single value (which is different from a "tuple" containing a single value) 您想将一个元组传递给cur.execute() ,就传递一个值(与包含单个值的“元组”不同)

also, why not do the date/time stuff in Postgres, it's pretty good at handling it. 同样,为什么不使用Postgres中的日期/时间,它在处理它上也很出色。 eg your query could be something like: 例如,您的查询可能类似于:

cur.execute("""SELECT * FROM "table" WHERE publishedAt > now() - interval '1 day'""")

otherwise you could do date calculations in the database with: 否则,您可以使用以下方法在数据库中进行日期计算:

cur.execute("""SELECT * FROM "table" WHERE publishedAt > %s - interval '1 day'""", (dt.datetime.now(),))

(notice the extra comma at the end), or do the calculation in Python with: (请注意末尾的逗号),或使用以下命令在Python中进行计算:

cur.execute("""SELECT * FROM "table" WHERE publishedAt > %s""", (dt.datetime.now() - dt.timedelta(days=1),))

if you want an upper limit on dates, you'd probably want to do something like: 如果您想要日期的上限,则可能需要执行以下操作:

now =  dt.datetime.now()
cur.execute("""SELECT * FROM "table" WHERE publishedAt BETWEEN %s AND %s""", (now - dt.timedelta(days=1), now))

(note that Python knows the brackets indicate a tuple so no trailing comma is needed) (请注意,Python知道方括号表示一个元组,因此不需要结尾逗号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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