[Python] How to pass tz-aware datetime instances to asyncpg?

Discussão em 'Python' iniciado por Stack, Setembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    When I do everything myself, explicitly, my query works fine:

    # start_ts is of PostgreSQL type "timestamp with time zone" aka "timestamptz"
    # start & end are datetime.datetime instances with tz=UTC
    query += f"WHERE start_ts >= '{ str(start) }'::timestamptz AND start_ts < '{ str(end) }'::timestamptz"
    await conn.fetch( query )


    When I try to pass them as args and let asyncpg safely interpolate them into the query string on my behalf:

    query += "WHERE start_ts >= $1::timestamptz AND start_ts < $2::timestamptz"
    await conn.fetch( query, start, end )


    I get this error:

    CannotCoerceError: cannot cast type text[] to timestamp with time zone


    What am I doing wrong?

    PS - I wish I could see that actual query that asyncpg is sending PostgreSQL, but I can't find anything in the docs or my google searches on how to enable that.

    Continue reading...

Compartilhe esta Página