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.
Related
I have these records in my database:
and I want to select them using python, however I only have the year and month which is stored in a variable:
Here is my code:
However this does not work, and I've only gotten it to work when using a fully specific date, e.g. 2022-06-11.
The values of the column Date in the table are strings in the proper format yyyy-MM-dd and you can use the operator LIKE:
c.execute("SELECT Category, Amount FROM transactions WHERE Date LIKE ? || '%'", (month_selected,))
or, with the function strftime():
c.execute("SELECT Category, Amount FROM transactions WHERE strftime('%Y-%m', Date) = ?", (month_selected,))
I'm new to Python and I'm interested to switch to Python all my current reporting's. As my reports include date frames, mostly of my reports include in the SQL query a "Start_Date" and an "End_Date". I have been looking around on how to write some line of code to do the same in python. Has anyone experienced the same, please help and share. My code is as follows:
import pandas as pd
import numpy as np
import cx_Oracle
import warnings
from datetime import date
from datetime import datetime as dtt
connstr = 'UN/PW#dbpath/DB' # this is hidden due to security
conn = cx_Oracle.connect(connstr)
today=date.today()
start_date = input("Enter start_date in MM/DD/YYYY format :")
month, year, day = map(int, start_date.split('/'))
end_date= input("Enter end_date in MM/DD/YYYY format :")
month, year, day = map(int, end_date.split('/'))
# a pop up will require to enter the start_date and the end_date manually
print (start_date)
print (end_date)
05/01/2021
05/31/2021
df=pd.read_sql_query("""select pr_no
, pr_task_no
, to_date(to_char(act_complete_date_time,'mm/dd/yyyy'),'mm/dd/yyyy') as act_complete_date_time
from pr_task
where pr_task_no = 100
and act_complete_date_time between to_date({start_date},'mm/dd/yyyy') and to_date({end_date},'mm/dd/yyyy')
""", conn)
The error that I'm getting is: DatabaseError: Execution failed on sql
': ORA-00936: missing expression
So Oracle is not recognizing the date entered and is not running the script.
I have give multiple attempts to format the date so it can be recognized from the database.
Can someone help to achieve this step?
Thank you in advance!
i think you are missing a "f" before the query string, as is
df=pd.read_sql_query(f"""select pr_no
, pr_task_no
, to_date(to_char(act_complete_date_time,'mm/dd/yyyy'),'mm/dd/yyyy') as act_complete_date_time
from pr_task
where pr_task_no = 100
and act_complete_date_time between to_date({start_date},'mm/dd/yyyy') and to_date({end_date},'mm/dd/yyyy')
""", conn)
without it you are sending the literal {start_date} to the db as the query and it is not replaced with the variable with the same name
as a side note, this code is considered vulnrable if you are letting an unknown user set the times, he or she could use sql injection to edit you query (imagine if instead of a date they put ;drop table pr_task)
I am using Python to connect to SQL Server database and execute several 'select' type of queries that contain date range written in a particular way. All these queries have the same date range, so instead of hard-coding it, I'd prefer to have it as a string and change it in one place only when needed.
So far, I found out that I can use datetime module and the following logic to convert dates to strings:
from datetime import datetime
start_date = datetime(2020,1,1).strftime("%Y-%m-%d")
end_date = datetime(2020,1,31).strftime("%Y-%m-%d")
Example of the query:
select * from where xxx='yyy' and time between start_date and end_date
How can I make it work?
EDIT
my code:
import pyodbc
import sqlalchemy
from sqlalchemy import create_engine
from datetime import datetime
start_date = datetime(2020,1,1).strftime("%Y-%m-%d")
end_date = datetime(2020,1,31).strftime("%Y-%m-%d")
engine = create_engine("mssql+pyodbc://user:pwd#server/monitor2?driver=SQL+Server+Native+Client+11.0")
sql_query = """ SELECT TOP 1000
[mtime]
,[avgvalue]
FROM [monitor2].[dbo].[t_statistics_agg]
where place = 'Europe' and mtime between 'start_date' and 'end_date'
order by [mtime] asc;"""
df = pd.read_sql(sql_query, engine)
print(df)
Thank you all for your input, I have found the answer to make the query work. The variables should look like:
start_date = date(2020, 1, 1)
end_date = date(2020, 1, 31)
and SQL query like:
sql_query = f""" SELECT TOP 1000
[mtime]
,[avgvalue]
FROM [monitor2].[dbo].[t_statistics_agg]
where place = 'Europe' and mtime between '{start_date}' and '{end_date}'
order by [mtime] asc;"""
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
I'm trying to have a start and end date as variables in a long SQL query in python that generates a dataframe. I've gone through the other posts regarding this and tried everything I know but I get errors and none of them work. I've shortened the sql query to show just the relevant part. Can anyone please give me any suggestions? I think the issue might have to do with the format of the date.
def get_dataframe():
startdate = 'input_startdate'
enddate = 'input_enddate'
query="""
where date between ? and ?
"""
params={'start':startdate, 'end':enddate}
conn = db.msSQLConnect()
df = pd.read_sql(query,conn,params)
return df
Remove quotes around startdate and enddate variable assignments.
With quotes literal string 'input_startdate' and 'input_enddate' are passed to the query, instead of the date values of the variables.
startdate = input_startdate
enddate = input_enddate