尝试不硬编码sql查询中的日期范围(python、sql server)

aemubtdh  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(320)

我正在使用python连接到sqlserver数据库并执行几个“select”类型的查询,这些查询包含以特定方式编写的日期范围。所有这些查询都有相同的日期范围,所以我不想硬编码它,而是希望它作为一个字符串,只在需要时在一个地方更改它。到目前为止,我发现我可以使用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)
6ju8rftf

6ju8rftf1#

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

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

相关问题