Search code examples
pythonicalendar

Sorting icalendar events chronologically


I need to convert a large set of ics icalendar events into a LaTeX pgfgantt chart. For this I wrote a tiny script with the help of an answer found here.

from icalendar import Calendar, Event
from datetime import datetime
from pytz import UTC # timezone

g = open('calendar.ics','rb')
gcal = Calendar.from_ical(g.read())
for component in gcal.walk():
    if component.name == "VEVENT":
        start = component.get('dtstart')
        end = component.get('dtend')
        print("\ganttbar{"+ str(component.get('summary')) + "}{" + str(start.dt) + "}{" + str(end.dt) + "}\\\\")
g.close()

The path has to be absolute for some reason.


Solution

  • Let's add the data into pandas and try to sort them according to the start date.

    from icalendar import Calendar, Event
    from datetime import datetime
    from pytz import UTC # timezone
    import pandas 
    
    g = open('calendar.ics','rb')
    gcal = Calendar.from_ical(g.read())
    calevents = pandas.DataFrame(columns=['Event','Start','End',])
    for component in gcal.walk():
        if component.name == "VEVENT":
            start = component.get('dtstart')
            end = component.get('dtend')
            calevents.loc[len(calevents)] = [component.get('summary'), start.dt, end.dt] 
    g.close()
    calevents['Start'] = pandas.to_datetime(calevents['Start'])
    calevents = calevents.sort_values(by='Start', ignore_index=True)
    for index in range(len(calevents)):
        print("\ganttbar{" + str(calevents.loc[index,"Event"]) + "}{" + str(calevents.loc[index,"Start"]) + "}{" + str(calevents.loc[index,"End"]) + "}\\\\")
    

    Almost there, but the first date now contains a time. Can be removed in the output by removing ' 00:00:00'.