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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| from datetime import datetime from icalendar import Calendar import csv import re
START_DATE = '#START_DATE' END_DATE = '#END_DATE' ICS_FILE_LOCATION = '#ICS_FILE_LOCATION' CSV_FILE_LOCATION = '#CSV_FILE_LOCATION'
class Convert2CSV(): def __init__(self): self.csv_data = []
def read_ical(self, ical_file_location): with open(ical_file_location, 'r', encoding='utf-8') as ical_file: data = ical_file.read() self.cal = Calendar.from_ical(data) return self.cal
def make_csv(self): for event in self.cal.subcomponents: if event.name != 'VEVENT': continue if datetime.combine(event.get('DTSTART').dt, datetime.min.time()) >= datetime.fromisoformat(START_DATE) and datetime.combine(event.get('DTEND').dt, datetime.min.time()) <= datetime.fromisoformat(END_DATE): row = [ event.get('DTSTART').dt.strftime("%Y-%m-%d"), event.get('DTEND').dt.strftime("%Y-%m-%d"), str(event.get('SUMMARY')), str(event.get('DESCRIPTION')), ] row = [x.strip() for x in row] self.csv_data.append(row)
def save_csv(self, csv_location): schema = ["Start Date", "End Date", "Summary", "Description"] with open(csv_location, 'w', encoding='utf-8') as csv_handle: writer = csv.writer(csv_handle) writer.writerow([h for h in schema]) for row in self.csv_data: writer.writerow([r.strip() for r in row])
Convert2CSV = Convert2CSV() Convert2CSV.ICS_FILE_LOCATION = ICS_FILE_LOCATION Convert2CSV.CSV_FILE_LOCATION = CSV_FILE_LOCATION
Convert2CSV.read_ical(Convert2CSV.ICS_FILE_LOCATION) Convert2CSV.make_csv() Convert2CSV.save_csv(Convert2CSV.CSV_FILE_LOCATION)
|