0

I wish to execute the statement to delete records from a postgresql table older than 45 days in my python script as below:

Consider only the code below:

import psycopg2
from datetime import datetime

cur = conn.cursor()
mpath = None
sql1 = cur.execute(
    "Delete from table1 where mdatetime < datetime.today() - interval '45 days'")

This causes the following error:

psycopg2.errors.InvalidSchemaName: schema "datetime" does not exist LINE 1: Delete from logsearch_maillogs2 where mdatetime < datetime.t...

How do I exactly change the format or resolve this. Do I need to convert. Saw a few posts which say that postgresql DateTime doesn't exist in PostgreSQL etc, but didn't find exact code to resolve this issue. Please guide.

0

1 Answer 1

0

The query is running in Postgres not Python you need to use SQL timestamp function not Python ones if you are writing a hard coded string. So datetime.today() --> now() per Current Date/time.

sql1 = cur.execute(
    "Delete from table1 where mdatetime < now() - interval '45 days'")

Or you need to use parameters per here Parameters to pass in a Python datetime if you want a dynamic query.


sql1 = cur.execute(
    "Delete from table1 where mdatetime < %s - interval '45 days'", [datetime.today()])

Sign up to request clarification or add additional context in comments.

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.