首页 > 解决方案 > 尽量不在 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)

标签: pythonsqlsqlalchemypyodbc

解决方案


谢谢大家的意见,我已经找到了使查询工作的答案。变量应如下所示:

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;"""

推荐阅读