Source

ical-stats / CalendarStats.py

Full commit
# -*- coding: utf-8 -*-

from icalendar import Calendar, vDatetime
from datetime import timedelta, datetime, date

class CalendarStats:
    def __init__(self, input_file, started_at, ended_at, duration, 
                 cat_included=[], cat_excluded=[]):
        self.ical = Calendar.from_string(open(input_file, 'rb').read())
        self.started_at = started_at
        self.ended_at = ended_at
        self.duration = duration

        self.cat_included = cat_included
        self.cat_excluded = cat_excluded

        self.events = []

    def get_events(self):
        if not self.events:
            self.events = []
            for event in self.ical.walk('vevent'):
                summary = event.decoded('summary')
                dtstart = event.decoded('dtstart')
                dtend = event.decoded('dtend')

                if date(dtstart.year, dtstart.month, dtstart.day) >= self.started_at and \
                        date(dtend.year, dtend.month, dtend.day) <= self.ended_at:
            
                    if self.cat_included:
                        if event.has_key('categories'):
                            for cat in event.decoded('categories').split(','):
                                if cat in self.cat_included:
                                    self.events.append(event)
                                    break
                    elif self.cat_excluded:
                        all_exclude = True
                        if event.has_key('categories'):
                            for cat in event.decoded('categories').split(','):
                                if cat not in self.cat_excluded:
                                    all_exclude = False
                        else:
                            all_exclude = False
                        if not all_exclude:
                            self.events.append(event)
                    else:
                        self.events.append(event)

        return self.events

    def display_events(self):
        for event in self.get_events():
            print event

    def hours_sum(self):
        diff = timedelta(0)
        for event in self.get_events():
            summary = event.decoded('summary')
            dtstart = event.decoded('dtstart')
            dtend = event.decoded('dtend')

            if isinstance(dtstart, datetime):
                diff += event.decoded('dtend') - event.decoded('dtstart')
            else:
                delta = event.decoded('dtend') - event.decoded('dtstart')
                diff += timedelta(hours=delta.days * self.duration)

        return diff.days*24 + diff.seconds / 3600.0