Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

420
Visualizações
What is the correct way of comparing SQL datetime objects and Python datetime objects in a query?

I am using Jupyter Notebooks and have connected my PostreSQL database like so:

%load_ext sql
from sqlalchemy import create_engine

I am using Python's datetime and the pytz library to create a timezone aware datetime object:

import pandas as pd
import datetime as dt
import pytz
from pytz import timezone

eastern = timezone('EST')

now = dt.datetime.now()
start = dt.datetime(now.year, now.month, now.day - 2, now.hour, now.minute, tzinfo=eastern)

Now when I am trying to make an SQL query, I do something like this to create a pandas DataFrame:

events_query = pd.read_sql(
    """\
        SELECT start_time,
        end_time,
        FROM events 
        WHERE room_id=2 
        AND deleted=false
        AND start_time < {}
        limit 3
    """.format(start), engine)

However, on the line start_time < {}, I get this error:

ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "14"
LINE 10:         and start_time < 2020-06-16 14:07:00-05:00

However, when I check the types and comparison values of the SQL start_time datatime object and my created Python datetime object, the comparison works normally (if I omit the start_time < {} comparison):

test = events_query['start_time'].values[0]
print(test)
print(start)
print(test > start)

This will print out:

2038-11-25 12:00:00-05:00
2020-06-16 14:07:00-05:00
True

What I have tried alternatively Instead of using .format() notation, I have also tried to use Python f-strings to insert the start variable, as well as using the % operator formatting. The error was the same for comparing start_time with a variable.

Sorry, this is my second time ever posting on SO, let me know if I formatted my question correctly.

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda