i have created a column for date using workbench now i have to update all the values of that column to current date either using sql query or using python code
mydb = mysql.connector.connect(host="localhost", user="root",
password="afif123", db="library")
mycursor = mydb.cursor()
fill = '''UPDATE issued_book SET Today = current_date()'''
mycursor.execute(fill)
#or
today = datetime.datetime.now()
fill = '''UPDATE issued_book SET Today = %s'''
mycursor.execute(fill, [today])
any of above two attempt doesn't helping
i have kept datatype of date column as DATETIME()
To do it in mysql, just modify your first query a bit...
update issued_book set today = now()
instead of current_date(), which is not a mysql function.
Related
I want to DELETE every 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 SQL like this:
cursor.execute("""
DELETE FROM alpaca_stock_prices_4H WHERE datetime = (?)
""", (last_Date))
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'))
""")
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.
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()])
I have a MS SQL Server DateTime field, and Im trying to search all records that are in between a date range:
mySqlString = "select * from users where signupDate >=#from and signupdate <=#to"
The two variables containing the date range come with format MM/dd/yyyy (dataFrom and dataTo, so Im replacing #from and #to at the string as follows:
datefrom = new Date(dataFrom);
dateto = new Date(dataTo);
req.input('from', sql.DateTime, datefrom )
req.input('to', sql.DateTime, dateto )
But I do not get any result.
What's the best approach to get this working properly?
You can always use CONVERT to accommodate your SQL query to your input format. In your case its format 101: select convert(varchar, getdate(), 101) ---> mm/dd/yyyy
So your query should look like
where (signupdate >= CONVERT(date, #from, 101)) AND (signupdate <= CONVERT(date, #to, 101))
This way you won't worry about the time of the stored date
req.input('from', sql.Date, (dataFrom))
req.input('to', sql.Date, (dataTo))
Assuming you checked if dataFrom and dataTo have valid dates.
I've got my data put into an SQLite3 database, and now I'm trying to work on a little script to access data I want for given dates. I got the SELECT statement to work with the date ranges, but I can't seem to add another condition to fine tune the search.
db columns id, date, driverid, drivername, pickupStop, pickupPkg, delStop, delPkg
What I've got so far:
import pandas as pd
import sqlite3
sql_data = 'driverperformance.sqlite'
conn = sqlite3.connect(sql_data)
cur = conn.cursor()
date_start = "2021-12-04"
date_end = "2021-12-10"
df = pd.read_sql_query("SELECT DISTINCT drivername FROM DriverPerf WHERE date BETWEEN :dstart and :dend", params={"dstart": date_start, "dend": date_end}, con=conn)
drivers = df.values.tolist()
for d in drivers:
driverDF = pd.read_sql_query("SELECT * FROM DriverPerf WHERE drivername = :driver AND date BETWEEN :dstart and :dend", params={"driver": d, "dstart": date_start, "dend": date_end}, con=conn)
I've tried a few different versions of the "WHERE drivername" part but it always seems to fail.
Thanks!
If I'm not mistaken, drivers will be a list of lists. Have you tried
.... params={"driver": d[0] ....
I am trying to filter the data from mongo using python code and available date format in mongo is quite different hence resulting zero records. I am trying to convert the date format but still it did not work.
One of the value from date field:
2018-06-28 21:27:31.132Z
I have connected to DB and using below code that returns zero records even though there are more than 1000 records available in DB.
I have tried by formatting as below
import datetime
date_time_str_st = '2018-03-07 23:22:29'
date_time_obj_st = datetime.datetime.strptime(date_time_str_st, '%Y-%m-%d %H:%M:%S')
date_time_str_en = '2018-03-08 00:07:44'
date_time_obj_en = datetime.datetime.strptime(date_time_str_en, '%Y-%m-%d %H:%M:%S')
foramtdt1 = date_time_obj_st.strftime("%Y-%m-%d %H:%M:%S.%fZ")
foramtdt2 = date_time_obj_en.strftime("%Y-%m-%d %H:%M:%S.%fZ")
pipeline = [{'$match':{'$and':[{'date':{'$gte': {'$date': '2018-03-07 23:22:29.683Z' }}},{'date':{'$lt': {'$date': '2018-03-08 00:07:44.629Z' }}}]}}]
Read_data = spark.read.format("com.mongodb.spark.sql.DefaultSource").option("uri",connectionstring).option("pipeline",pipeline).load()
display(Read_data)
Also tried using direct filter
pipeline = [{'$match':{'$and':[{'date':{'$gte': '2018-03-07 23:22:29.683Z'}},{'date':{'$lt': '2018-03-08 00:07:44.629Z' }}]}}]
Readdata = spark.read.format("com.mongodb.spark.sql.DefaultSource").option("uri",connectionstring).option("pipeline",pipeline).load()
display(Readdata)
0 records are filtering. I believe i am not properly converting required timestamp format. Can anyone help me on this?