I am making an api call and in doing so I have to manually change the endDate in the payload every day. I can not use .format() inside a dictionary. Can anyone help out?
Current payload: where I am changing the endDate manually
payload = "{\"dimensions\":[\"AdsetId\",\"Adset\",\"CampaignId\",\"Campaign\",\"Device\",\"Day\",\"Month\",\"Year\",\"Week\",\"Os\"],\"metrics\":[\"AdvertiserCost\",\"Displays\",\"ClickThroughRate\",\"Cpc\",\"AppInstalls\",\"Clicks\"],\"timezone\":\"UTC\",\"advertiserIds\":\"69957\",\"currency\":\"USD\",\"startDate\":\"2022-01-01T00:00:00.0000000+00:00\",\"***endDate\":\"2022-01-13***T00:00:00.0000000+00:00\",\"format\":\"csv\"}"
Expected payload:
payload = "{\"dimensions\":[\"AdsetId\",\"Adset\",\"CampaignId\",\"Campaign\",\"Device\",\"Day\",\"Month\",\"Year\",\"Week\",\"Os\"],\"metrics\":[\"AdvertiserCost\",\"Displays\",\"ClickThroughRate\",\"Cpc\",\"AppInstalls\",\"Clicks\"],\"timezone\":\"UTC\",\"advertiserIds\":\"69957\",\"currency\":\"USD\",\"startDate\":\"2022-01-01T00:00:00.0000000+00:00\",\endDate\":\"{}T00:00:00.0000000+00:00\",\"format\":\"csv\"}".format(today)
Here today will be a variable with today’s date
>Solution :
That’s a string, not a dictionary and the .format thing that you want, works. Guessing that this is in fact JSON data, the normal way to do this sort of thing is to build a python dict and serialize it later. Using a python "f-string" makes it simple to call a function in the string format specification itself. datetime.datetime.utcnow() gives the current UTC time. It can be converted to a date and its isoformat method writes the format you want. So,
import datetime as dt
import json
data = {
"dimensions": ["AdsetId", "Adset", "CampaignId", "Campaign",
"Device", "Day", "Month", "Year", "Week", "Os"],
"metrics": ["AdvertiserCost", "Displays", "ClickThroughRate",
"Cpc", "AppInstalls", "Clicks"],
"timezone": "UTC",
"advertiserIds": "69957",
"currency": "USD",
"startDate": "2022-01-01T00:00:00.0000000+00:00",
"endDate": f"{dt.datetime.utcnow.date.isoformat()}T00:00:00.0000000+00:00",
"format": "csv"}
payload = json.dumps(data)
print(payload)