Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

414
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda