Dec 19, 2015

iCal Birthday calendar from CSV

My father was as nice to write down his birthday calendar notes electronically. I wanted to use this for me and return the favor if he ever gets excited about keeping track of these things digitally. Main learning points in an early iteration were the writing of files in python (see "wb") and some "getting to know" with the csv module. Thunderbird has a special way to mark the day as a whole-day event, see this Writeup via icalevents.com.

In this posted version, I quit doing .split ops on the strings and integer conversions and import the time via a defined format and strptime. I formerly added for every event a calendar.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3
#
# convert birthday csv-list to .ics readable by thunderbird-lightning calendar
# km@jify.de 2015-12-19

import sys, csv, pytz
from datetime import datetime, timedelta
from icalendar import Calendar, Event

with open(sys.argv[1], newline='') as csvfile, open('output.ics', 'wb') as icsfile:

    data = csv.reader(csvfile, delimiter=';', quotechar='|', skipinitialspace=True)

    cal = Calendar()
    cal.add('prodid', '-//py3 csv2ical thunderbird// purzel.py//')
    cal.add('version', '0.5')

    for row in data:

        localtime = pytz.timezone("Europe/Berlin")

        fmt = "%d.%m.%Y"
        bday = datetime.strptime(row[0], fmt).replace(tzinfo=localtime)
        bdayend = timedelta(days=+1)
        #bdayend = bday.replace(hour=23,minute=59,second=00)

        day = datetime.strftime(bday, "%d")
        month = datetime.strftime(bday, "%m")
        year = datetime.strftime(bday, "%Y")

        notes = row[1] + ' (' + year +')'

        event = Event()

        event.add('summary', notes)
        event.add('dtstart;value=date', bday.strftime("%Y%m%d"))
        event.add('dtend', bday + bdayend)
        event.add('dtstamp', datetime.now())
        event.add('rrule', {'freq': 'yearly', 'bymonth': month, 'bymonthday': day})

        cal.add_component(event)

    icsfile.write(cal.to_ical())