Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete sqlite3 record from a table WHERE datetime contains date from a variable

I want to DELETE every sqlite3 record with a datetime (e.g. 2022-11-10T??????????) using a date (e.g. 2022-11-10) from a variable.

for example:

last_Date = datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d')

and use sqlite code to something like this;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cursor.execute("""
DELETE FROM alpaca_stock_prices_4H WHERE datetime = (?)
""", (last_Date))

>Solution :

The value of the variable last_Date is a formatted as YYYY-MM-DD date string but the column datetime in the table contains timestamps in the format YYYY-MM-DDT?????????? so you can’t compare them with the = operator.

Use SQLite’s strftime() or date() function to format the datetimes also to YYYY-MM-DD:

cursor.execute("""
DELETE FROM alpaca_stock_prices_4H WHERE strftime('%Y-%m-%d', datetime) = ?
""", (last_Date,))

or:

cursor.execute("""
DELETE FROM alpaca_stock_prices_4H WHERE date(datetime) = ?
""", (last_Date,))

If what you actually want is delete all yesterday’s rows you can do it without passing a parameter, by using only SQL code:

cursor.execute("""
DELETE FROM alpaca_stock_prices_4H WHERE date(datetime) = date('now', '-1 day'))
""")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading