As you can tell I'm new to python, and struggling with the correct way/syntax to iterate over date ranges in my Google Analytics API call. The master function iterates over specific Website View IDs already (I have it loop through the 'client_id', but I'm wondering what the correct way to have it iterate over date ranges would be/where I need to put it in my code.
Right now I am running it using the GA Date Dimension to get daily results, but I also need to run it for MTD, 7 Day Rolling, and 30 Day rolling iterations. Here is a sample the code I am using.
def APmain(client_id):
base_df = pd.DataFrame()
columns = traffic_columns
start_date = datetime.strptime(master_startdate , '%Y-%m-%d').date()
end_date = datetime.strptime(master_enddate , '%Y-%m-%d').date()
filters = 'ga:screenResolution!=0x0'
print('Running Google Analytics Report.')
#change based the type and number of dimensions pulled. These are set
dimensions = 'ga:'+(',ga:'.join(columns[:3]))
metrics = 'ga:'+(',ga:'.join(columns[3:]))
results = analytics_get_report(client_id, str(start_date), str(end_date), dimensions, metrics, filters)
df = pd.DataFrame(results, columns=columns)
df['view_id'] = client_id
df['filter_type'] = 'New'
df['dimension'] = 'SourceMedium'
df['DateType'] = 'Daily'
base_df = base_df.append(df)
base_df = base_df.applymap(str)
base_df = base_df[base_df.date != '(other)'] #remove if date column has '(other)' as a value
base_df['date'] = pd.to_datetime(base_df['date'], format='%Y%m%d') #format date
# Powershell output
print(base_df.head())
#bigquery output
base_df.to_gbq(
'', #dataset name + table name
'', #project name
chunksize=10000,
reauth=False,
if_exists='append',
credentials=credentials
)
I have a variables names 'master_startdate' and 'master_enddate' where I define the date range I have it pull data for currently. I've messed around with something like this but can't get it to work correctly, but I feel like I'm on the right track and/or thinking about it correctly.
import calendar
from datetime import datetime, timedelta, date
import calendar
cal= calendar.Calendar()
wholeyear= range(0,365)
master_start_date= '2019-01-01'
start_date= datetime.strptime(master_start_date , '%Y-%m-%d').date()
end_date2= datetime.strptime(end_date , '%Y-%m-%d').date()
for x in wholeyear:
end_date = start_date + (timedelta(days=1)*x)
print(end_date)
pass
start_date2= datetime.date.today()
start_date2= datetime.date(end_date2.year(),end_date2.month(),1)
print(start_date2)
Any help for a beginner here would be greatly appreciated!