python - 如何使用python按日期过滤postgresql查询
问题描述
在我的 postgres 中,我有一个字段created_at和updated_at。我正在使用python使用游标查询数据库。问题是,当我在 python 字符串中传递日期以按created_at列过滤时,出现错误
TypeError:“日期时间”类型的对象不是 JSON 可序列化的
当我将这两个字段转换为varchar()时,我能够得到结果。如果不强制转换两个字段,我怎样才能得到相同的结果?
询问
SELECT
id,
CAST(created_at AS varchar(40)),
CAST(updated_at AS varchar(40)),
amount
FROM
public.table_1
WHERE created_at >= (%s) and created_at <= (%s);
Python
def read_latest_data_from_pg(**kwargs):
with open('dags/scripts/sql_scripts/pg_export_sql/sql_file.sql','r') as sqlfile:
pg_export_data_query=str(sqlfile.read())
max_1 = '2021-05-01'
max_2= '2021-05-28'
pg_hook = PostgresHook(postgres_conn_id='pg_conn', delegate_to=None, use_legacy_sql=False)
conn = pg_hook.get_conn()
cursor = conn.cursor()
cursor.execute(pg_export_data_query, (max_1 , max_2))
result = cursor.fetchall()
print('result', result)
return result, len(result)
解决方案
假设在 postgresql 中列 created_at 和 updated_at 是“日期”或“没有时区的时间戳”,您只需调整您的 sql,因此无需转换它,并以日期时间格式传递输入。
注意:我已经直接使用 psycopg2 来让这个查询工作。
from django.http import JsonResponse
cur = con.cursor()
today = datetime.date.today()
first = today.replace(day=1)
# last day of month
max1 = first - datetime.timedelta(days=1)
# first day of month
max2 = max1.replace(day=1)
sql = "SELECT id, created_at, updated_at, amount FROM public.table_2 WHERE created_at >= %s::date and created_at <= %s::date"
cur.execute(sql, (max2, max1))
result = cur.fetchall()
return JsonResponse({ 'result': result } , safe=False)
推荐阅读
- php - AWS CDN 域名变更
- asp.net-mvc - 如何在 ASP.NET MVC 中用千位分隔符格式化网格列的字符串?
- r - 查找具有可选前导字符串后跟可选空格的字符串,两者都具有否定的lookbehind
- drupal-8 - 在电子邮件中发送礼品卡代码 - Drupal 商务
- postgresql - 当postgresql中没有值时如何将布尔值设置为空?
- reactjs - 设置新道具后酶包装不显示新状态
- java - 自定义注释不适用于 @JsonProperty
- reactjs - 如何使用 useEffect 避免无限循环
- javascript - (React)子组件在父组件重新渲染时暂停其 useEffect
- mysql - Flask 应用设置问题:PyCharm 运行时配置