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

415
Vistas
Querying database for documents within a specified date range using FastAPI and MongoDB

I have a collection in my MongoDB with records that have an attribute "timestamp" which is stored as type datetime

I want to use FastAPI to query and return all records which are within a given range of dates that I am passing on as query parameters.

db = client["tasks"]

async def list_activities(
    lower_date: str = "", upper_date: str = ""
):
    start_date = datetime.strptime(lower_date, "%d-%m-%Y")
    end_date = datetime.strptime(upper_date, "%d-%m-%Y")
    activities = (
        await db["activities"]
        .find({"timestamp": {"$gte": start_date, "$lt": end_date}})
        .to_list(1000)
    )
    return activities

On running this with some parameters for lower and upper dates, I'm being returned an empty list

However I wrote another program to test this

MONGODB_URL = os.getenv("MONGODB_URL")
mc = pymongo.MongoClient(MONGODB_URL)
tgdb = mc["tasks"]
tgcol = tgdb["activities"]
recordno = 1

for x in tgcol.find(
    {"timestamp": {"$gte": "2022-01-31 00:00:00", "$lt": "2022-02-06 00:00:00"}}
):
    print("Record No: " + str(recordno))
    recordno += 1
    print(x)

This on the other hand returns all the records within the date range just fine.

Any clue as to what I'm doing wrong with the first piece of code?

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