DateExpiry in Sqlite3 Python - 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')

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.

Get the closest date to a date in a mysql query

So I have a table in MySQL which stores a name and a date. I want to write a query that gets the closest date to a certain date I have determined. For example, I have:
x = datetime(2022, 01, 01)
This:
query = "SELECT date_ FROM set_payment7777 GROUP BY name"
mycursor.execute(query)
for cursor in mycursor:
print(cursor)
is currently printing all the dates from the table grouped by name. I want to add something to make it print all the dates for each name that is closer to the variable x.
For instance, if we have the entries in the table: "06-06-2021, James" also "06-07-2021, James" and "04-04-2021, Helen" also "05-04-2021, Helen" it should print: 06-07-2021 and 05-04-2021.
I hope you understand.
If I can understand the problem you can try this solution using it on the result of your query:
import pandas as pd
from datetime import datetime
df = pd.DataFrame({'date': ['06/06/2021', '06/07/2021', '04/04/2021', '05/04/2021' ],
'name': ['James', 'James', 'Helen', 'Helen']})
df['date'] = pd.to_datetime(df['date'])
data_point = datetime(2022, 1, 1)
df['data_diff'] = df['date'] - data_point
# abs data_diff
df['data_diff'] = df['data_diff'].abs()
# select the rows where data_diff is less than a month
df['data_end'] = df['data_diff'].apply(lambda x: x.days)
Since the comparison date is greater than all the dates in the table, you can reduce the problem to finding the greatest date for each name:
SELECT name, MAX(date)
FROM set_payment7777
GROUP BY name

Sqlite3 search column by providing Year and month

The Following function create a table in sqlite3:
def create_table(mycursor):
mycursor.execute('''CREATE TABLE IF NOT EXISTS ch_details(id INTEGER PRIMARY KEY autoincrement,
ch_id TEXT, ch_date DATETIME DEFAULT CURRENT_DATE, ch_no TEXT, cli TEXT, vhs_no TEXT, f_lo TEXT,
t_lo TEXT, qty REAL, adv REAL DEFAULT 0 , oth_de REAL DEFAULT 0, ch_amt REAL DEFAULT 0, mem_id TEXT,
UNIQUE(ch_id));''')
which stores my date in Datetime in ch_date column however when
i try to get the last row of ch_id column in this table stored by providing specific month/year using the following code:
def gen_chid():
dt, mt, yr = cal_gen.get().split("/")
conn = sqlite3.connect('database/u_data.vita')
mycursor = conn.cursor()
mycursor.execute("SELECT ch_id FROM ch_details WHERE strftime('%Y%m', ch_date)",yr, mt)
row = mycursor.fetchone()
The code gets this error:
TypeError: function takes at most 2 arguments (3 given)
The can_gen.get() gets the date from entry box in "07/07/2021" string format
I have also checked this stack answer link but did not get any result.
SQLite's datetime functions like strftime() work only if the datetime values that are passed to them have the format YYYY-MM-DD for dates or YYYY-MM-DD hh:mm:ss for datetimes.
If you stored the dates in the format DD/MM/YYYY then the only way to extract the date parts like day, month or year is by treating the date as a string and use string functions like SUBSTR():
def gen_chid():
conn = sqlite3.connect('database/u_data.vita')
mycursor = conn.cursor()
sql = """
SELECT ch_id
FROM ch_details
WHERE SUBSTR(ch_date, 4) = ?
"""
mycursor.execute(sql, (cal_gen.get()[3:],))
row = mycursor.fetchone()
Here SUBSTR(ch_date, 4) extracts the month/year part in the format MM/YYYY and it is compared to the substring returned from cal_gen.get() after the 3d char which is passed to execute() as the only member of a list.

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')
;

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

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))

Categories