Created
April 11, 2012 14:14
-
-
Save sligodave/2359553 to your computer and use it in GitHub Desktop.
User a list of when all users joined.
This file contains 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
from datetime import datetime | |
######################################### | |
# Set up the django environment | |
######################################### | |
from django.core.management import setup_environ | |
import settings | |
setup_environ(settings) | |
from django.contrib.auth.models import User | |
######################################### | |
# Set the granularity of the report | |
######################################### | |
GRANULARITIES = { | |
'y': (lambda x: [x.year, 1, 1], | |
'%Y'), | |
'm': (lambda x: [x.year, x.month, 1], | |
'%Y-%m'), | |
'd': (lambda x: [x.year, x.month, x.day], | |
'%Y-%m-%d'), | |
'H': (lambda x: [x.year, x.month, x.day, x.hour], | |
'%Y-%m-%d %H:%M'), | |
'M': (lambda x: [x.year, x.month, x.day, x.hour, x.minute], | |
'%Y-%m-%d %H:%M'), | |
} | |
def get_granulatity_options(granularity): | |
return GRANULARITIES[granularity] | |
def group_users_by_join_date(date_fields): | |
grouped_users = {} | |
for u in User.objects.all().values_list('date_joined'): | |
join_date = datetime(*date_fields(u[0])) | |
grouped_users.setdefault(join_date, 0) | |
grouped_users[join_date] += 1 | |
return grouped_users | |
def convert_to_list(grouped_users, date_format): | |
grouped_users_keys = grouped_users.keys() | |
grouped_users_keys.sort() | |
return ["%s: %d" % (x.strftime(date_format), grouped_users[x]) | |
for x in grouped_users_keys] | |
if __name__ == "__main__": | |
from sys import argv | |
granularity = 'y' if len(argv) == 1 else argv[1] | |
date_fields, date_format = get_granulatity_options(granularity) | |
grouped_users = group_users_by_join_date(date_fields) | |
total_user_count = sum(grouped_users.values()) | |
for grouping in convert_to_list(grouped_users, date_format): | |
print grouping | |
print 'Total Users: %d' % total_user_count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I may extend to allow for the passing of a django settings file path that can be imported instead of presuming it's on the path as settings.py