代码之家  ›  专栏  ›  技术社区  ›  EMP

如何为时间戳(日期时间)的数组指定psycopg2参数

  •  9
  • EMP  · 技术社区  · 15 年前

    我想使用psycopg2在python中运行一个postgresql查询,它按类型的列进行过滤 timestamp without timezone . 我有一长串时间戳(而不是范围)的允许值,并且psycopg2可以方便地处理数组,所以我认为这应该可以工作:

    SELECT somestuff
    FROM mytable
    WHERE thetimestamp = ANY (%(times)s)
    

    这个 times 参数是 datetime 物体。我也试过了 psycopg2.Timestamp() .它们都翻译成 WHERE thetimestamp = ANY (ARRAY['2009-07-06T00:00:00', '2009-07-07T00:00:00', ...]) 不幸的是,失败的原因如下:

    operator does not exist: timestamp without time zone = text
    LINE 3: WHERE thetimestamp = ANY (ARRAY['2009-07-06T00:00:00', '2009-07-07T00:00:00', ...]
    HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
    

    我已经在pgadmin中确认了这一点,所以这不仅仅是psycopg2。似乎发生的是Postgres不会将字符串数组隐式转换为时间戳数组。如果我显式地添加 ::timestamp 对于pgadmin中的每个元素,但我不知道如何在psycopg2中这样做。

    除了忘记DB-API参数和手工构建长时间戳之外,最好的方法是什么?我能不能把它转换成正确的类型?

    2 回复  |  直到 14 年前
        1
  •  12
  •   Ants Aasma    15 年前

    尝试如下:

    SELECT somestuff
    FROM mytable
    WHERE thetimestamp = ANY (%(times)s::timestamp[])
    
        2
  •  3
  •   Peter Eisentraut    14 年前

    如果使用psycopg2 2.2.0或更高版本,则如果将值包装在 Timestamp() 如您所建议的,构造函数。

    它以前不起作用的原因是psycopg2实现中的一个bug。建议的解决方法是将显式强制转换插入到SQL中,如另一个答案所建议的那样。