I am getting an error while retrieving data of the last month using python. What is the best approach for the given piece of code?
last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1) start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day) previous_month_data = "SELECT * from " + tableName + " between UsageDateTime " + str(start_day_of_prev_month) + " AND " + str(last_day_of_prev_month) print(previous_month_data) mycursor.execute(previous_month_data) results = mycursor.fetchall() pd.set_option("display.max_columns",70) df = pd.DataFrame(results) print(df)
I am not able to get solution, What changes can I do. I am using MYSQL as my source database and Python 3.7.4 as my programming language.
Since error is big, posting it in two parts :
Part1
Part2
Advertisement
Answer
You are missing a WHERE
clause:
previous_month_data = "SELECT * FROM " + tableName + " WHERE UsageDateTime BETWEEN '" + str(start_day_of_prev_month) + "' AND '" + str(last_day_of_prev_month) + "'"
But I prefer to use ?
placeholders for the parameters and pass them as a tuple:
previous_month_data = "SELECT * FROM " + tableName + " WHERE UsageDateTime BETWEEN ? AND ?" mycursor.execute(previous_month_data, (str(start_day_of_prev_month), str(last_day_of_prev_month)))
Note that if the column UsageDateTime
‘s data type is DATETIME
or TIMESTAMP
then instead of WHERE UsageDateTime BETWEEN ...
you should use WHERE DATE(UsageDateTime) BETWEEN ...
, otherwise you will miss the rows of the last day of the month.