Python:在Python Script中将'Start_date'和'End_date'作为SQL下的变量嵌入



我使用Python连接到Amazon Redshift来拉数据,下面的部分是执行SQL部分。('engine'和相关库已经定义)

try_data = pd.read_sql_query(text(try_sql), engine)
try_data.head(3)

如果'start_date'和'end_date'在SQL查询下硬编码,则可以正常工作,如:

try_sql = """
select * from users where created_at >= '2019-07-01' and created_at < '2021-07-01' limit 10
;
"""

但是如果我尝试将start_dateend_date定义为变量然后将其放入查询中则失败:

start_date = '2019-07-01'
end_date = '2021-07-01'
try_sql = """
select * from users where created_at >= '", start_date , "' and created_at < '", end_date , "' limit 10
;
"""

带有错误消息:(psycopg2.errors.InvalidDatetimeFormat)日期类型的输入语法无效:", start_date, ">

我怎样才能改变它?谢谢!

现在try_sql返回

select * from users where created_at >= '", start_date , "' and
created_at < '", end_date , "' limit 10;
使用<<p> strong>格式字符串你可以这样做
try_sql = f"""
select * from users where created_at >= '{start_date}' and created_at < '{end_date}' limit 10;
"""

,它将返回

select * from users where created_at >= '2019-07-01' and created_at < '2021-07-01' limit 10;

最新更新