使用 Python 检索上个月的数据,源为 MYSQL

Retrive data of last month using Python with source as MYSQL

我在使用 python 检索上个月的数据时遇到错误。给定代码段的最佳方法是什么?

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)

我无法得到解决方案,我可以做些什么改变。我使用 MYSQL 作为我的源数据库和 Python 3.7.4 作为我的编程语言。

由于误差较大,所以分两部分贴出:

第一部分

enter image description here

第二部分

enter image description here

UsageDateTime 字段的数据类型是什么。 如果是datetime,试试这个。

previous_month_data = "SELECT * from " + tableName + " between UsageDateTime CAST(" + str(start_day_of_prev_month) + " AS DATE) AND CAST(" + str(last_day_of_prev_month) + " AS DATE"

您缺少 WHERE 子句:

previous_month_data = "SELECT * FROM " + tableName + " WHERE UsageDateTime BETWEEN '" + str(start_day_of_prev_month) + "' AND '" + str(last_day_of_prev_month) + "'"

但我更喜欢对参数使用 ? 占位符并将它们作为元组传递:

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

请注意,如果列 UsageDateTime 的数据类型是 DATETIMETIMESTAMP,那么您应该使用 WHERE DATE(UsageDateTime) BETWEEN ... 而不是 WHERE UsageDateTime BETWEEN ...,否则您将错过该月最后一天的行。

我建议将 f 字符串用于 sql 带有变量的查询:

previous_month_data = f'''SELECT * from {tableName}  WHERE UsageDateTime  between {start_day_of_prev_month} AND {last_day_of_prev_month}'''