Пример #1
0
def _generate_stats(time_min, time_max, events):
    """
    Generate stats from a list of events.

    @param events: list(events), events to analyze
    @param time_min: datetime, from time
    @param time_max: datetime, to time
    @return: dict(), stats object
    """

    num_events = 0
    event_days = defaultdict(lambda: 0)
    attendees = 0
    total_duration_in_secs = 0
    event_series = defaultdict(lambda: 0)
    for event in events:
        try:
            _ac = event['_ac'] = {}
            if 'dateTime' not in event['start']:
                # All-day events
                continue

            # TODO: Sort out declined and tentative events, if not
            # event.organizer.self, find self in event.attendees
            # list(dict)), 'email' = self and 'responseStatus' =
            # 'accepted'
            start = str_to_datetime(event['start']['dateTime'])
            end = str_to_datetime(event['end']['dateTime'])

            _ac['duration'] = end - start

            if event.get('summary', '') == 'Lunch':
                # Don't count lunches as events
                continue
            if end.hour < WORK_DAY_START or start.hour > WORK_DAY_END:
                # TODO: will miss multi-day events
                continue
            if start.weekday() > 4 or end.weekday() > 4:
                # TODO: will exclude events ending or starting in
                # weekends, but stretching into the week
                continue

            _ac['included'] = True
            total_duration_in_secs += _ac['duration'].total_seconds()
            event_series[start.date()] += 1
            event_days[start.weekday()] += 1
            num_events += 1
            # if list not present, Default to 1 attendant (self)
            attendees += len(event.get('attendees', ['1']))
        except Exception:
            logging.exception('Could not process: {0}'.format(event))
            raise

    # Calculate stats
    stats = {}
    stats['events'] = num_events
    stats['event_days'] = OrderedDict((v, event_days[k]) for (k, v) in WEEKDAY_TO_STR.iteritems())
    stats['event_series'] = OrderedDict((timegm(k.timetuple()) * 1000, v) for (k, v) in sorted(event_series.iteritems()))
    stats['event_hours'] = total_duration_in_secs / 60 / 60
    stats['working_days'] = num_working_days(time_min, time_max)
    stats['working_hours'] = (WORK_DAY_END - WORK_DAY_START) * stats['working_days']
    stats['percent_events'] = (stats['event_hours'] / stats['working_hours']) * 100
    stats['avg_attendees'] = attendees / stats['events']
    stats['avg_events_day'] = stats['events'] / stats['working_days']
    stats['events_excluded'] = len(events) - stats['events']

    return stats