sql - 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?
解决方案
尝试将其嵌入到查询字符串中,如下所示:
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'
推荐阅读
- solace - 为队列不工作的多个消费者提供安慰
- python - 根本不使用续行,但得到“语法错误:行续符后的意外字符”。初级水平
- junit - 如何在 Spring 5 中使用 webtestclient 为服务组件类编写 Junit
- python - python中的“不确定”日期时间对象?
- angular - 无法在角度 4 的多个组件中使用自定义组件
- angular - Angular 6 路由重定向
- node.js - 如何添加后反应电报机器人 node.js
- spring-boot - 如何在 JHipster 应用程序中跟踪用户活动
- php - 函数描述的符号表示如何在 php.net 上工作
- c# - 在 umbraco 中渲染子页面