I am using python to execute the query and retrieve the data from Google Ads I am trying to set start and end date as variable and use these in my query.
The query looks like this:
GAquery = """
SELECT
segments.date,
segments.device,
campaign.name,
metrics.clicks,
metrics.conversions,
metrics.conversions_value,
metrics.cost_micros,
metrics.impressions
FROM
campaign WHERE segments.date >= '2021-12-01' AND segments.date <= '2022-02-27'
ORDER BY
metrics.clicks DESC"""
and it is executed by Google Function for Python
response = ga_service.search_stream(customer_id=customer_id, query=GAquery)
This function does not have element params where i could use %s as placeholder in the query and then call it in params regular execute(sql,conn, params[Sdate,Edate] function in python.
So what i need to do is somehow break the query string, and add the dates in between. Something like this:
sdate = (dt.date.today() - dt.timedelta(days=60))
edate = dt.date.today()
GAquery = """
SELECT
segments.date,
segments.device,
campaign.name,
metrics.clicks,
metrics.conversions,
metrics.conversions_value,
metrics.cost_micros,
metrics.impressions
FROM
campaign WHERE segments.date """ + """>= """+ str(sdate) +""" AND segments.date""" + """<=""" +str(edate) + """
ORDER BY
metrics.clicks DESC"""
So basically i am trying to force variables into GAquery by breaking the query apart inserting it and stitching it together.
It is failing because i am not breaking it correctly and not adding it back together correctly.
Any idea how to handle this?
To me it looks as if you're missing the single quotes that are required for a date literal in GAQL. In order to parametrize the query, you could use a formatted string literal (assuming you are using Python 3.6 or newer) and do something like
GAquery = f"""
SELECT
...
FROM
...
WHERE
segments.date >= '{str(sdate)}' AND segments.date <= '{str(edate)}'
ORDER BY
...
"""