首页 > 解决方案 > 如何使用python按日期过滤postgresql查询

问题描述

在我的 postgres 中,我有一个字段created_atupdated_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)

标签: pythonpostgresql

解决方案


假设在 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)

在此处输入图像描述


推荐阅读