0

Error when using timedelta from datetime.now() in SQL Server where clause

python 3.6

yesterday = datetime.now() - timedelta(days=1)

sql = "SELECT submit_dt, api_job_name, job_status, xml_record_count, x_successful_number, x_failed_number, " \
      f"job_run_time, mf_job_name FROM JOB_LOG where submit_dt > {yesterday}"

try:
    db = Database()
    db.cursor.execute(sql)
    rows = db.cursor.fetchall()

SQL ODBC Error: Incorrect syntax near '22' --- which is the time part of the datetime.

I've tried wrapping it in '' but then get convert from string error.

2 Answers 2

1

Consider parameterizing your query without any need of string conversion of datetime or string interpolation including F-strings.

yesterday = datetime.now() - timedelta(days=1)

sql = """SELECT submit_dt, api_job_name, job_status, xml_record_count, 
                x_successful_number, x_failed_number, 
                job_run_time, mf_job_name 
         FROM JOB_LOG 
         WHERE submit_dt > ?"""

try:
    db = Database()
    db.cursor.execute(sql, yesterday)
    rows = db.cursor.fetchall()
Sign up to request clarification or add additional context in comments.

Comments

0

The error was due to including the microseconds in the compare value. I was able to use:

yesterday_sql = yesterday.strftime("%Y-%m-$d %H:%M:%S")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.