EMP*_*EMP 9 python postgresql timestamp psycopg2 python-db-api
我想使用psycopg2在Python中运行PostgreSQL查询,psycopg2按类型列进行过滤timestamp without timezone.我有一个很长的时间戳允许值列表(而不是一个范围)和psycopg2方便地处理数组,所以我认为这应该工作:
SELECT somestuff
FROM mytable
WHERE thetimestamp = ANY (%(times)s)
Run Code Online (Sandbox Code Playgroud)
该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.
Run Code Online (Sandbox Code Playgroud)
我也在pgAdmin中证实了这一点,所以它不仅仅是psycopg2.似乎正在发生的事情是Postgres不会隐式地将字符串数组转换为时间戳数组.它会很好地转换单个字符串,如果我明确地添加::timestamp到pgAdmin中的每个元素,数组工作正常,但我不知道如何在psycopg2中这样做.
除了忘记DB-API参数并且只是手动构建长串时间戳之外,最好的方法是什么?有什么方法可以让它投射到正确的类型?
Ant*_*sma 13
试试这样:
SELECT somestuff
FROM mytable
WHERE thetimestamp = ANY (%(times)s::timestamp[])
Run Code Online (Sandbox Code Playgroud)