Created
July 28, 2020 12:56
-
-
Save robflaherty/5633db5bae928415b3f68f4141f5af22 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Main | |
def main(interval): | |
global API | |
API = initialize_analyticsreporting() | |
start_date = datetime.strptime(START_DATE, '%Y-%m-%d').date() | |
end_date = datetime.strptime(END_DATE, '%Y-%m-%d').date() | |
cache = defaultdict(int) | |
counts = [] | |
# Subtract 1 because GA date ranges are inclusive | |
delta = timedelta(days=interval -1) | |
# Make a query for each day and get the users who visited that day | |
while start_date <= end_date: | |
query_end = start_date + delta | |
print (start_date.strftime('%Y-%m-%d')) | |
print (query_end.strftime('%Y-%m-%d')) | |
result = fetch_data(start_date.strftime('%Y-%m-%d'), query_end.strftime('%Y-%m-%d')) | |
# Add users to the dictionary | |
for row in result: | |
id = row.get('dimensions')[0] | |
cache[id] += 1 | |
# Increment start date | |
start_date = query_end + timedelta(days=1) | |
# Total number of user ids in query | |
total_users = len(cache) | |
# Make a list of all the counts | |
for k, v in cache.items(): | |
counts.append(v) | |
# Calculate the visit counts and sort by key (day) | |
counted = sorted(Counter(counts).items()) | |
# Flatten to a list | |
output = [i[1] for i in counted] | |
# Display as percentages | |
percentages = [int(round(i/total_users * 100, 0)) for i in output] | |
# Print results | |
print('Total Users:') | |
print(total_users) | |
print('\n') | |
print('Daily Visit Counts:') | |
print(output) | |
print('\n') | |
print('Daily Visit Percentages:') | |
print(percentages) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment