What sqlite3 query for "date range" condition that i can use? - python

I'm using python and sqlite3, and i'm trying to select data from my database, based on input date range.
since = input("Enter date since = ")
dateuntil = input("Enter date until = ")
year, month, day = map(int, since.split('-'))
since = datetime.date(year, month, day)
year, month, day = map(int, dateuntil.split('-'))
dateuntil = datetime.date(year, month, day)
connection, cursor = connect_db()
cursor.execute("select * from dates where myDate BETWEEN ? AND ?;", since, dateuntil)
alldata = cursor.fetchall()
But, it shows "TypeError: function takes at most 2 arguments (3 given)". Any suggestion below would be highly appreciated. Thank you

cursor.execute takes 2 arguments: the query and the query args tuple.
You need to change since, dateuntil to a 2-element tuple: (since, dateuntil):
cursor.execute("select * from dates where myDate BETWEEN ? AND ?;", (since, dateuntil))

Related

How to select dates in SQLite with python

Im trying to query a table, and need to grab all products that have a date = today date.
Below is my code so far
import sqlite3
from datetime import date
date = date.today()
con = sqlite3.connect('test.db')
cur = con.cursor()
date = date.today()
sql_q = f'''SELECT date, name FROM table WHERE date = {date}'''
table = cur.execute(sql_q)
for row in table:
print(row)
i am using an SQlite 3 db and all data has been entered with the following format:
2022-09-20
However this variable type does not seem to work with SQL.
i know the SQL code should look somthing like this
SELECT name FROM test WHERE date = '2022-09-20'
but i'd like the date to be selected automatically from python rather than typing it in manually.
Use the function date() to get the current date:
SELECT name FROM test WHERE date = date()
or CURRENT_DATE:
SELECT name FROM test WHERE date = CURRENT_DATE
I think you need to convert date to string and then pass it in query.
maybe your datatype of column and date.today() is different.
date = date.strftime('%Y-%m-%d')
try using this.

SQL DATABASE datetime date query

Getting error for below how to put date in variable for sql query?
for symbol in symbolist:
datereplace1 = '2022-04-03 00:00:00'
datereplace2 = '2022-04-03 00:00:00'
query=(f"""DELETE FROM {symbol} WHERE Time >=%s AND Time <%s""", ) #we can also delete older than x days by writing thisWHERE col <= date('now', '-10 day')
cursor.execute(query, (datereplace1,datereplace2))
test.commit()
cursor.execute(query, (datereplace1,datereplace2))
TypeError: argument 1 must be str, not tuple

Python lookup mysql for value 1 week, 1 month, ytd and 1 year

Hi I am developing a stocks portfolio tracker. As part of this I am pulling all my listed stocks from one website which gives a performance % of 1 week, 1 month, YTD and 1 year. Some of my other investments which I am needing to pull figures for individually only gives the current price as of that day.
I am storing all my data in a mysql database using python (pymysql library currently). What I want to know is how can I do a lookup of a value at the various time periods. I know how I could just do lookup 1 week etc. however sometimes there will be no data on that particular day and I need to just get the either the closest record or the last prior or the next record (not that fussy).
tblHistory with fields rDate, rStockID, rPrice among other fields
Query something like this but varDate1Week is an approximate which won't always have an "EXACT" match
"SELECT rPrice FROM tblHistory WHERE (rStockID = " + str(varStockID) + " AND rDate = " + varDate1Week + ")"
My Sample Code after Luuk's assistance.
import datetime
import pymysql
db = pymysql.connect(host='localhost',user='Test',password='TestPassword',database='dbInvest')
varrDate2 = datetime.datetime.now().strftime("%Y-%m-%d")
cursor2 = db.cursor(pymysql.cursors.DictCursor)
sqllookup = "SELECT rPrice FROM tblHistory WHERE rStockID = 7 and rDate >= DATE_ADD('2021-06-20', INTERVAL - 7 DAY) ORDER BY rDATE LIMIT 1"
cursor2.execute(sqllookup)
Perform1WeekList = cursor2.fetchall()
print ("1 Week Value is " + str(Perform1WeekList[0]))
cursor2.close
The output I get from this is
1 Week Value is {'ClosePrice': Decimal('86.7400')}
Would like to be able to use variable varrDate2 in place of hard coded date. Also to have clean output (ie. 86.7400). I could do it with a split and then a replace on the string but sure there is a better way.
In MySQL you can do:
SELECT
t1.rPrice,
(SELECT t2.rPrice
FROM tblHistory t2
WHERE t2.rStockID = t1.rStockID
and t2.rDate <= DATE_ADD(t1.rDate,INTERVAL -7 DAY)
ORDER BY r2.rDate DESC
LIMIT 1) "1weekago"
(SELECT t3.rPrice
FROM tblHistory t3
WHERE t3.rStockID = t1.rStockID
and t3.rDate <= DATE_ADD(t1.rDate,INTERVAL -30 DAY)
ORDER BY r3.rDate DESC
LIMIT 1) "30daysago"
FROM tblHistory t1
WHERE (t1.rStockID = 1 AND t1.rDate = '2021-06-19')
;

DateExpiry in Sqlite3 Python

I try to figure out how to write function with SQLite3 statement which is responsible for informing me about expiry date of any medicine in advance let's suppose 30 days. I did sth like this but it doesn't work properly
l1top = Label(fr,text="Number of serie:")
l1top.grid(row=0,column=0,padx=20,sticky=E,pady=10)
l2top = Label(fr,text="Name of medicine:")
l2top.grid(row=1,column=0,padx=20,sticky=E,pady=10)
l3top = Label(fr,text="Dose")
l3top.grid(row=3,column=0,padx=20,sticky=E,pady=10)
l4top = Label(fr,text="Type of medicine")
l4top.grid(row=4,column=0,padx=20,sticky=E,pady=10)
l5top = Label(fr,text="Packages:")
l5top.grid(row=5,column=0,padx=20,sticky=E,pady=10)
l5top = Label(fr,text="Bottles:")
l5top.grid(row=6,column=0,padx=20,sticky=E,pady=10)
l6top = Label(fr,text="Expiry Date:")
l6top.grid(row=7,column=0,padx=20,sticky=E,pady=10)
def expiry():
conn = sqlite3.connect("pharmacy.db")
cur = conn.cursor()
cur.execute('SELECT date FROM medicine WHERE date <= 30')
matched = [rec[0] for rec in cur]
conn.close()
items = [row for row in tree.get_children() if tree.item(row, 'values')[6] in matched]
tree.selection_set(items)
expiry()
The code above doesn't select properly because it matches only according to days but it does not include the whole date from the widget DateEntry(below). How to rewrite the SQLite statement that it grabs the whole date and matches all products with date which expiry ends in 30 days and highlights on red the last column ([6]) with date.
e6 = DateEntry(fr,width=12,bg="darkblue",fg="white",year=2020,state="readonly",date_pattern="dd/mm/yyyy",textvariable=six)
e6.grid(row=7,column=1,pady=10)
If the format of the column date is DD-MM-YYYY, first you must change it to YYYY-MM-DD, because this is the only valid format for SQLite:
UPDATE medicine
SET date = SUBSTR(date, -4) || '-' || SUBSTR(date, 4, 2) || '-' || SUBSTR(date, 1, 2);
and then use the function DATE() to get the rows where date is between now and now + 30 days:
SELECT date
FROM medicine
WHERE date BETWEEN DATE('now') AND DATE('now', '+30 day')

How can I get the amount of days between two dates?

I got a python script, which is supposed to fetch data of my mysql table (contains a date) and then it should print out the amount of days between today´s date and the date of my mysql table.
I already tried substracting the two dates, but this wouldn´t work. So I tried substracting today´s date and my birthday, which worked. So I think the problem is the mysql date.
import datetime
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database='appointments'
)
eventDate = mydb.cursor()
eventDate.execute('SELECT event_date FROM appointdatetitle')
Date = eventDate.fetchall()
tdelta = datetime.timedelta(days=7)
today = datetime.date.today()
eday = Date
till_eday = eday - today
print(till_eday.days)
Date = eventDate.fetchall() fetchall actually fetches a tuple of tuples
e.g.
(('abcd',), ('efgh',))
You would want to get the Date by looping over the list and getting the elements. e.g.
for d in Date:
#This will contain the date you need
print(d[0])
Or you can directly access an element by doing say Date[0][0]
After update from OP, this is what can be done!
OP can use https://dateutil.readthedocs.io/en/stable/index.html to use the
from dateutil.relativedelta import * to increment the month!
import datetime
from dateutil.relativedelta import *
Date = [(datetime.date(2019, 4, 24),)]
#Extract actual datetime object from Date variable
date_obj = Date[0][0]
#Increment month by 1 since January starts from 0
date_obj += relativedelta(months=1)
today = datetime.date.today()
#Using datetime from above
eday = date_obj
till_eday = eday - today
print(till_eday.days)
The output will be 23

Categories