如何在Python中设置和引用日期范围,然后应用到查询中?

kjthegm6  于 2023-01-08  发布在  Python
关注(0)|答案(2)|浏览(141)

这就是我想在Spyder中做的事情

from datetime import datetime, date
start_date = date(year=2022, month=8, day=9)
end_date = date(year=2022, month=9, day=16)

start_date_str = start_date.strftime("%Y-%m-%d")
end_date_str = end_date.strftime("%Y-%m-%d")

test_query = """
SELECT COUNT(DISTINCT(advertising_id)) FROM dataset
WHERE group_assignment = "TEST" AND day BETWEEN "{start_date}" AND "{end_date}"
"""

我收到错误[3:49]无法将文字“{start_date}”转换为DATE类型我如何在查询中引用python中的代码?似乎很难找到答案
我需要在python中设置一个固定的日期,这样我就不必在python中使用bigquery来更改每个查询的日期

k4emjkb1

k4emjkb11#

from datetime import datetime

# Set the start date to January 1st, 2020
start_date = datetime(2020, 1, 1)

# Set the end date to December 31st, 2020
end_date = datetime(2020, 12, 31)

更多信息here

flvtvl50

flvtvl502#

正如其中一个注解所正确指出的,代码块要求f是f字符串(格式化字符串常量的缩写)。
就这样。
代码如下所示:

from datetime import datetime, date
start_date = date(year=2022, month=8, day=9)
end_date = date(year=2022, month=9, day=16)

start_date_str = start_date.strftime("%Y-%m-%d")
end_date_str = end_date.strftime("%Y-%m-%d")

test_query = f"""
SELECT COUNT(DISTINCT(advertising_id)) FROM dataset
WHERE group_assignment = "TEST" AND day BETWEEN "{start_date}" AND "{end_date}"
"""

print(test_query)

结果是这样的:

SELECT COUNT(DISTINCT(advertising_id)) FROM dataset
WHERE group_assignment = "TEST" AND day BETWEEN "2022-08-09" AND "2022-09-16"

相关问题