Search code examples
pythonpostgresqldatetimepsycopg2

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


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

I see the "publishedAt" field, returns a datetime.datetime value.

# 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?


Solution

  • 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)

    also, why not do the date/time stuff in Postgres, it's pretty good at handling it. e.g. 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:

    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)