TypeError:'Datetime.Datetime'对象不支持索引 [英] TypeError: 'datetime.datetime' object does not support indexing

查看:25
本文介绍了TypeError:'Datetime.Datetime'对象不支持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的24小时内,我在查询表中的所有数据时遇到了困难,很难说这是否是我的一部分的Postgres错误,因为我是初学者

我看到"Publishedat"字段返回一个日期时间.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)), .....]

但是,

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

结果:

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

是否可以在心理拷贝g2查询中使用DateTime库?

推荐答案

如果要将元组传递到cur.execute(),则传递的是单个值(这与包含单个值的"元组"不同)

另外,为什么不在postgres中处理日期/时间的内容,它在处理它方面做得很好。例如,您的查询可能如下所示:

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

否则您可以使用以下命令在数据库中进行日期计算:

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

(请注意末尾的额外逗号),或使用以下命令在Python中进行计算:

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

如果您想要日期的上限,您可能需要执行以下操作:

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

(请注意,Python知道括号表示元组,因此不需要尾随逗号)

这篇关于TypeError:'Datetime.Datetime'对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆