首页 > 解决方案 > SQL select query in Python code within specific date range

问题描述

When I run the below SQL query within Python code, it will display me the rows I wanted (hardcoded way).

sql = 'SELECT column1, column2 FROM xyz_table where <date_column> like "2019-12-%" ORDER BY <date_column> desc'

I just wanted some help to run the same query but make it reliable as the query is supposed to run every month.

sql= 'SELECT column1, column2 FROM xyz_table where <date_column> like (datetime.date.today().replace(day=1) - datetime.timedelta(days=1)).strftime("%Y-%m-%") ORDER BY <date_column> desc'

In the above command, datetime is not working within the SQL query and I have searched but didn't find any way to use datetime within SQL query.

Can someone help me in finding a way to select data from table within specific dates using the Python code?

标签: sqlpython-3.xdatetime

解决方案


尝试将其嵌入到查询字符串中,如下所示:

sql= f'SELECT column1, column2 FROM xyz_table where <date_column> like {(datetime.date.today().replace(day=1) - datetime.timedelta(days=1)).strftime("%Y-%m-%")} ORDER BY <date_column> desc'

更新:上一行引发错误,以下示例应该有效:

import datetime
dt = (datetime.date.today().replace(day=1) - datetime.timedelta(days=1)).strftime('%Y-%m-')
sql= f'SELECT column1, column2 FROM xyz_table where <date_column> like "{dt}%" ORDER BY <date_column> desc'

推荐阅读