I'm getting the following error while running my sql in python
/usr/lib/python2.6/site-packages/django/db/backends/mysql/base.py:64: RuntimeWarning: SQLite received a naive datetime (2012-06-22 15:53:43) while time zone support is active.
my query also returns the wrong data.
if i change the time up 2 hours (17:53:43 instead of 15:53:43), my timezone atm is gmt +2 so i think the problem is in the time zone.
how do i change my query to make the sql execute in the way i intend it to?
sql:
sqlQuery = """SELECT w.id, w.serial, w.finishdate, w.weighingtype_id, w.netto, w.bruto, w.deleted
FROM weighing w
LEFT JOIN weighing w1
ON w1.id = w.parent_id
WHERE w.user_id = %(userid)s"""
if date:
sqlQuery = sqlQuery + " AND (w.created = %(date)s OR w.modified > %(date)s)"
edit: added my code for transforming the datetime
data = request.GET.copy()
if 'date' in data:
try:
data['date'] = datetime.datetime.strptime(data['date'], "%Y-%m-%dT%H:%M:%S")
except:
raise error(311)
Related
I'm trying to get the script to automatically set the query start time as 6am yesterday (and will set the end time as 6am today once I figure out the Start time error) but I am getting a syntax error (102, b"Incorrect syntax near '06'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n").
If I take out the """+StartTime+""" and change to '20211212 07:00:00.000' then it works but I need a way for the script to keep track of the current date rather than going back and changing every day.
from datetime import timedelta
import numpy as np
from pandas import DataFrame
import pandas as pd
import pymssql
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
BEGINDATE=yesterday
ENDDATE=today
BEGINDATE=BEGINDATE.strftime("%Y%m%d")
ENDDATE=ENDDATE.strftime("%Y%m%d")
StartTime = BEGINDATE +' 06:00:00:000'
print(StartTime)
Query= """SET NOCOUNT ON
DECLARE #StartDate DateTime
DECLARE #EndDate DateTime
SET #StartDate = """+StartTime+"""
SET #EndDate = '20211213 07:00:00.000'
SET NOCOUNT OFF
SELECT temp.TagName ,DateTime ,Value ,vValue ,MinRaw = ISNULL(Cast(AnalogTag.MinRaw as VarChar(20)),'N/A') ,MaxRaw = ISNULL(Cast(AnalogTag.MaxRaw as VarChar(20)),'N/A') ,Unit = ISNULL(Cast(EngineeringUnit.Unit as VarChar(20)),'N/A') ,StartDateTime From (
SELECT *
FROM History
WHERE History.TagName IN ('S03_FT03_04_TOT01')
AND wwRetrievalMode = 'Cyclic'
AND wwCycleCount = 1440
AND wwVersion = 'Latest'
AND DateTime >= #StartDate
AND DateTime <= #EndDate) temp
LEFT JOIN AnalogTag ON AnalogTag.TagName =temp.TagName
LEFT JOIN EngineeringUnit ON AnalogTag.EUKey = EngineeringUnit.EUKey
WHERE temp.StartDateTime >= #StartDate"""
cur.execute(Query)
print(Query)
Consider running parameterization in Python passed into a prepared SQL statement without declaring # params. Also, keep all variables in datetimes without any string conversion.
Not quite sure what your date ranges require given 6 AM and 7 AM confusion, below calculates range from yesterday at 6 AM to today at 5:59:59 AM (for 24 hours). Adjust as needed. Finally, final WHERE is moved into subquery.
from datetime import datetime, date, timedelta
import numpy as np
from pandas import DataFrame
import pandas as pd
import pymssql
BEGINDATE = datetime.combine(
date.today() - timedelta(days = 1), datetime.min.time()
) + timedelta(hours = 6)
print(BEGINDATE)
# 2021-12-12 06:00:00
ENDDATE = BEGINDATE + timedelta(days = 1) - timedelta(seconds=1)
print(ENDDATE)
# 2021-12-13 05:59:59
### PREPARED STATEMENT WITH %s PLACEHOLDERS
Query= """SELECT temp.TagName
, [DateTime]
, [Value]
, vValue
, MinRaw = ISNULL(CAST(AnalogTag.MinRaw AS VARCHAR(20)), 'N/A')
, MaxRaw = ISNULL(CAST(AnalogTag.MaxRaw AS VARCHAR(20)), 'N/A')
, Unit = ISNULL(CAST(EngineeringUnit.Unit AS VARCHAR(20)), 'N/A')
, StartDateTime
FROM (
SELECT *
FROM History
WHERE History.TagName IN ('S03_FT03_04_TOT01')
AND wwRetrievalMode = 'Cyclic'
AND wwCycleCount = 1440
AND wwVersion = 'Latest'
AND [DateTime] >= %s
AND [DateTime] <= %s
AND StartDateTime >= %s
) temp
LEFT JOIN AnalogTag ON AnalogTag.TagName = temp.TagName
LEFT JOIN EngineeringUnit ON AnalogTag.EUKey = EngineeringUnit.EUKey
"""
# RUN QUERY WITH PARAMETERS
cur.execute(Query, [BEGINDATE, ENDDATE, BEGINDATE])
print(Query)
Having trouble passing parameters to a SQL Server query. The query works with raw data, but not when I try to use parameters. SQL is not identifying parameter markers.
The error I get is
The SQL contains 0 parameter markers, but 2 parameters were supplied', 'HY000'
This is my code I'm having issues with:
currenttime = datetime.datetime(year=2021, month=6, day=7, hour=7, minute=0, second=0, microsecond=999999)
print(currenttime)
print(type(currenttime))
starttime = currenttime = datetime.datetime(year=2021, month=6,day=7,hour=6,minute=0,second=0,microsecond=999999)
params = (starttime,currenttime)
sql='''
SET QUOTED_IDENTIFIER OFF
SELECT * FROM OPENQUERY(INSQL, "SELECT DateTime, [AH41_DP04]
FROM WideHistory
WHERE wwRetrievalMode = 'Cyclic'
AND wwResolution = 1000
AND wwVersion = 'Latest'
AND DateTime >= ?
AND DateTime <= ?")
'''
print(type(params))
cursor.execute(sql,params)
for row in cursor:
print(row)``
I'm trying to send today variable into SQL but it is not working.
import datetime from date
today = date.today()
stmt = "select agent_email from customer_interaction_fact where to_date(DT) >= + today + ORDER BY CONVERSATION_CREATED_TIME DESC"
You don't have to compute today's date in Python. Just use the PostgreSQL function CURRENT_DATE:
stmt = "SELECT ... WHERE TO_DATE(DT) >= CURRENT_DATE ..."
What database engine you're using? You'd need to convert the python datetime object into string with format accepted by the database.
# In case YYYY-MM-DD
today_str = str(today)
stmt = f"""select agent_email
from customer_interaction_fact
where to_date(DT) >= datetime({today}, "YYYY-MM-DD")
order by CONVERSATION_CREATED_TIME DESC"""
Another solution, assuming the client (your program) is in the same timezone as the database engine, you could use your database engine datetime.now function. In SQLite for instance datetime('now')
try like below
from datetime import date
today = date.today()
stmt = "select agent_email,aht_in_secs,queueid,EFFORTSCORE from facts.public.customer_interaction_fact where agent_email <> 'Bot' and aht_in_secs is not NULL and to_date(DT) >=" + today + "ORDER BY CONVERSATION_CREATED_TIME DESC"
I'm making Car parking system, and I have some difficulities with SQL database.
I'm selecting data from SQL database, but I need to get the time correctly that I could use it for further calculations. So for example I need to get the time that was inserted to database as VARCHAR, maybe the bad thing is that I needed to use other method as TIME, but that's not the case. The thing I need is to use this line Started_Parking = row [3]. This should get the time from database and after that, I should be able to see the time difference from the start when car was registered and current time. By doing that I should be able to calculate the sum which the "User" should pay for parking.
So by short I just need to somehow get the time from database and use it for calculations. Here's my code, I also get errors when compiling :
Error while fetching data from PostgreSQL unsupported operand type(s)
for -: 'datetime.datetime' and 'str'
try:
connection = psycopg2.connect(user="postgres",
password="Dziugas420",
host="127.0.0.1",
port="5432",
database="postgres")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from vartotojai WHERE carnum=('%s')" % car_numb
cursor.execute(postgreSQL_select_Query) # PALEIST KOMANDA
vartotoju_data = cursor.fetchall() # READ DATA
print(" CAR DETAILS: ")
for row in vartotoju_data:
print("Current ID: ", row[0])
print("Car Number: ", row[1])
print("Parked on: ", row[3], "\n")
Pay_Time = datetime.datetime.now()
Started_Parking = row [3]
Prastovetas_Laikas = Pay_Time - Started_Parking
print(Prastovetas_Laikas)
# NOW LET'S CHECK IF THE TIME DIFFERENCE IS WORKING, LET'S SEE THE DIFFERENCE AFTER 20SECS.
time.sleep(20)
Pay_Time2 = datetime.datetime.now()
Prastovetas_Laikas2 = Pay_Time2 - Started_Parking
print(Prastovetas_Laikas2)`
**EDIT
Here's the code I use to import this time into database:
Car_Reg_Time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
postgres_insert_query = """ INSERT INTO vartotojai (CARNUM, TIME, LAIKAS) VALUES (%s,%s, %s)"""
record_to_insert = (car_numb, Reg_Tikslus_Laikas, Car_Reg_Time)
And here's the table of my database:
! laikas in database is when car was registered, the time in database is the time when the injection was made.
Prastovetas_Laikas = Pay_Time - Started_Parking
will not work
since Pay_Time is datetime.datetime and Started_Parking is str
you need to try to use datetime.strptime() to convert Started_Parking to correct type
and you want to store them as str in your DB using str(mydate)
Im using a raspberry pi with the rasbpian wheezy distribution running headless. I currently have a cronjob that runs a python script to put the current temperature and datetime in a mySQL database
(table: tempLog, attributes: datetime, temperature float(5,2)).
I want to delete rows that are say 5 days (num days is arbitrary) old and i'm having trouble accomplishing this in python. Here is the code, its not long.
import os
import time
import datetime
import glob
import MySQLdb
from time import strftime
from datetime import timedelta
from datetime import date
# Variables for MySQL
db = MySQLdb.connect(host="localhost", user="root",passwd="password", db="temp_database")
cur = db.cursor()
del_basedate = datetime.datetime.today() - timedelta(1)
# DATE_SUB(NOW() , INTERVAL 1 DAY)
try:
cur.execute("DELETE FROM tempLog WHERE datetime.date.day = del_basedate")
print "Delete successful"
except:
print "An error occured in: deleteRows.py"
finally:
cur.close()
db.close()
I had to do sever import from, because it kept throwing errors of objects not existing.
You need to learn about coding context:
del_basedate = datetime.datetime.today() - timedelta(1)
^^----python variable
cur.execute("DELETE FROM tempLog WHERE datetime.date.day = del_basedate")
text string with the letters "d", "e", "l", "_", etc... --- ^^^
Python isn't magical, and will NOT rummage around in a string to see if any of the text in that string LOOKS like a python variable. So you're effectively telling your DB to compare datetime.date.day against some unknown/undefined del_basedate field.
Try
cur.execute("DELETE FROM tempLog WHERE datetime.date.day = '" + del_basedate + "'")
^^^^^^^^^^^^^^^^^^
Note the extra quotes within the string. Without them, you'd be comparing against = 2016-02-18, which is a math operation, and is parsed/executed by the database as = 1996