python - 尽量不在 SQL 查询中硬编码日期范围(Python、SQL 服务器)
问题描述
我正在使用 Python 连接到 SQL Server 数据库并执行几个“选择”类型的查询,这些查询包含以特定方式编写的日期范围。所有这些查询都具有相同的日期范围,因此与其硬编码,我更愿意将其作为字符串并仅在需要时在一个位置进行更改。到目前为止,我发现我可以使用 datetime 模块和以下逻辑将日期转换为字符串:
from datetime import datetime
start_date = datetime(2020,1,1).strftime("%Y-%m-%d")
end_date = datetime(2020,1,31).strftime("%Y-%m-%d")
查询示例:
select * from where xxx='yyy' and time between start_date and end_date
我怎样才能让它工作?
编辑我的代码:
import pyodbc
import sqlalchemy
from sqlalchemy import create_engine
from datetime import datetime
start_date = datetime(2020,1,1).strftime("%Y-%m-%d")
end_date = datetime(2020,1,31).strftime("%Y-%m-%d")
engine = create_engine("mssql+pyodbc://user:pwd@server/monitor2?driver=SQL+Server+Native+Client+11.0")
sql_query = """ SELECT TOP 1000
[mtime]
,[avgvalue]
FROM [monitor2].[dbo].[t_statistics_agg]
where place = 'Europe' and mtime between 'start_date' and 'end_date'
order by [mtime] asc;"""
df = pd.read_sql(sql_query, engine)
print(df)
解决方案
谢谢大家的意见,我已经找到了使查询工作的答案。变量应如下所示:
start_date = date(2020, 1, 1)
end_date = date(2020, 1, 31)
和 SQL 查询,如:
sql_query = f""" SELECT TOP 1000
[mtime]
,[avgvalue]
FROM [monitor2].[dbo].[t_statistics_agg]
where place = 'Europe' and mtime between '{start_date}' and '{end_date}'
order by [mtime] asc;"""
推荐阅读
- html - 如何从选择器中排除一个 div 元素和他的所有孩子?
- html - 使用纯 HTML/CSS 创建播放/暂停按钮?
- amazon-web-services - 如何使用无服务器框架在 aws aurora 无服务器中自动创建表
- html - 在 safari 或移动设备上,内容没有用边界半径填充 div
- python - 一个令人困惑的对象组合python代码
- oracle - 为什么 SPOOL COMMAND 在 RHEL 中不起作用?
- constraints - 如何在具有 3 个整数变量的线性规划中定义“当且仅当”
- package.json - 如果看起来 react-i18next 依赖于 i18next,如何将 react-i18next 添加到 package.json?
- maven - Maven 程序集插件 - 忽略“存档不能为空”
- gradle - 使用 Gradle 从另一个项目导入测试