Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

413
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!