def get_ics(self, filename): try: with open('../Test_Files/' + filename + '.ics', 'rb') as icsF: cal = Calendar.from_ical(icsF.read()) #csvF = open('../New_Files/' +filename + '.csv', 'w') rows = [['SUMMARY', 'DTSTART', 'DTEND', 'NOTES', 'LOCATION']] for component in cal.walk(): if component.name == "VEVENT": row = [] #f = row.append(str(component.get('summary'))) # Extract and format the date accordingly start = vDatetime.from_ical( component.get('dtstart').to_ical().decode()) row.append(str(start.strftime('%m-%d-%Y %I:%M %p'))) end = vDatetime.from_ical( component.get('dtend').to_ical().decode()) row.append(str(end.strftime('%m-%d-%Y %I:%M %p'))) row.append(str(component.get('description'))) row.append(str(component.get('location'))) #make sure any data types are covered for i in range(len(row)): if row[i] == 'None' or row[i] == None: row[i] = '' #else: # row[i] = '"'+row[i]+'"' #print (row) rows.append(row) self.table = rows except FileNotFoundError: print('File does not exist')
def get_parameters(self): for component in self.calendar.walk('vevent'): client = component.get('summary') if client: start = vDatetime.from_ical(component.get('dtstart').to_ical()) end = vDatetime.from_ical(component.get('dtend').to_ical()) hours = (end-start).seconds // 3600 # end - start is a timedelta # We only store day month and year to after index them nicely booking_key = date(start.year,start.month,start.day) if booking_key > self.last_booking_date: self.last_booking_date = booking_key # Update the bookings dictionary if booking_key in self.bookings: self.bookings[booking_key][start] = (end,client) else: self.bookings[booking_key] = {start : (end,client)} # Update the clients_hours dictionary if client in self.clients_hours: self.clients_hours[client] += hours else: self.clients_hours[client] = hours self.total_hours_booked += hours
def findMonthEvts(self, dayList, listCalendar): #Define the start and end limit start = dayList[0] end = dayList[-1] month_evt = {} for n, calendar in enumerate(listCalendar): if calendar['activate'] == "true": start_date = '%04d%02d%02d' % (start['year'], start['month'], start['number']) end_date = '%04d%02d%02d' % (end['year'], end['month'], end['number']) print n, calendar if calendar['typeaccount'] == "google": start_date = '%04d-%02d-%02d' % ( start['year'], start['month'], start['number']) end_date = '%04d-%02d-%02d' % (end['year'], end['month'], end['number']) events = self.googleCalendar.return_calendar_events( calendar['login'], calendar['password'], calendar['url'], start_date, end_date) for e in events: month_evt[e] = "event" elif calendar['typeaccount'] == "local": #Traitment of the local iCalendar File url = translatePath(calendar['url']) cal = Calendar.from_string( open(os.path.join(url), 'rb').read()) for evt in cal.walk('VEVENT'): a = '%04d%02d%02d' % ( vDatetime.from_ical(evt['dtstart'].ical()).year, vDatetime.from_ical(evt['dtstart'].ical()).month, vDatetime.from_ical(evt['dtstart'].ical()).day) if a >= start_date and a <= end_date: month_evt[a] = "event" elif calendar['typeaccount'] == "web": pass return month_evt
def extract_info(file_name, this_list): now = time.strftime("%Y-%m-%d"); now = now + " " + time.strftime("%H:%M:%S"); g = open(this_path+'/'+file_name,'rb') gcal = Calendar.from_ical(g.read()) for component in gcal.walk(): if component.name == "VEVENT": start = component.get('dtstart') year = str(start.dt) year = year[:4] if(year<"2015"): continue start_time = aslocaltimestr(vDatetime.from_ical(start.to_ical())) temp_time = start_time.split(' ',3) final_time = str(temp_time[0]) temp_time[1] = temp_time[1].split('.',2) final_time = final_time + " " + str(temp_time[1][0]) if final_time < now: continue; this_summary = str(component.get('summary')) fstr = final_time+" --> "+this_summary this_list.append(fstr) g.close() return this_list
def eventlist_as_html(entries): '''Take a list of icalendar.Calendar entries; format it as a list of events in HTML, returned as a string. Writes to icalendar format as an intermediary because that's the easiest way to get icalendar.Calendar to parse its date ''' html = '''<table border=1 summary="This table shows the calendar of events. Each row is an event. Columns contain the event date, time, and description which includes the location"> <caption>Calendar of Events</caption> <thead> <tr> <th id="date" width="15%">Date</th> <th id="time" width="10%">Time</th> <th id="description">Description and Place</th> </tr> </thead> <tbody>''' year = None for cal in entries: print("cal['DTSTART'] = %s" % cal['DTSTART']) # cal['DTSTART'] might be a icalendar.prop.vDDDTypes object # or it might be a string. Handle either type: try: starttime = cal['DTSTART'].dt except AttributeError: starttime = vDatetime.from_ical(cal['DTSTART']) if not year or starttime.year != year: year = starttime.year html += '''<tr> <td colspan="3"><h4>%d</h4></td> </tr>''' % year datestr = starttime.strftime("%A,<br />%B %d") timestr = "" html += '''<tr> <td headers="date">%s</td><td headers="time">%s</td> <td headers="description"><span class="alert">%s</td></tr>''' \ % (datestr, timestr, cal['SUMMARY']) # Seems like it would be better to use # cal['SUMMARY'].encode('utf-8', 'xmlcharrefreplace')) # but python gives an error, # UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 # in position 43: ordinal not in range(128) html += '''</tbody> </table> <!-- calendar table -->''' return html
def eventlist_as_html(entries): '''Take a list of icalendar.Calendar entries; format it as a list of events in HTML, returned as a string. Writes to icalendar format as an intermediary because that's the easiest way to get icalendar.Calendar to parse its date ''' html = '''<table border=1 summary="This table shows the calendar of events. Each row is an event. Columns contain the event date, time, and description which includes the location"> <caption>Calendar of Events</caption> <thead> <tr> <th id="date" width="15%">Date</th> <th id="time" width="10%">Time</th> <th id="description">Description and Place</th> </tr> </thead> <tbody>''' year = None for cal in entries: print "cal['DTSTART'] =", cal['DTSTART'] # cal['DTSTART'] might be a icalendar.prop.vDDDTypes object # or it might be a string. Handle either type: try: starttime = cal['DTSTART'].dt except AttributeError: starttime = vDatetime.from_ical(cal['DTSTART']) if not year or starttime.year != year: year = starttime.year html += '''<tr> <td colspan="3"><h4>%d</h4></td> </tr>''' % year datestr = starttime.strftime("%A,<br />%B %d") timestr = "" html += '''<tr> <td headers="date">%s</td><td headers="time">%s</td> <td headers="description"><span class="alert">%s</td></tr>''' \ % (datestr, timestr, cal['SUMMARY']) # Seems like it would be better to use # cal['SUMMARY'].encode('utf-8', 'xmlcharrefreplace')) # but python gives an error, # UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 # in position 43: ordinal not in range(128) html += '''</tbody> </table> <!-- calendar table -->''' return html
def testTzinfoDt(self): mo = dt.datetime(2020, 2, 2, 2, tzinfo=dt.timezone.utc) v = vDt(mo) self.assertTrue(v) self.assertEqual(v, mo) self.assertEqual(v, vDatetime(mo)) self.assertEqual(v, vDatetime.from_ical("20200202T020000Z")) self.assertEqual(v.date(), mo.date()) self.assertEqual(v.time(), mo.time()) self.assertEqual(v.datetime(), mo) self.assertEqual(v.tzinfo(), mo.tzinfo) self.assertEqual(v.zone()[:3], "UTC") # changed in Python 3.6 self.assertEqual(v.timezone(), dt.timezone.utc)
def testNaiveDt(self): mo = dt.datetime(1987, 6, 21, 3, 54, 0) v = vDt(mo) self.assertTrue(v) self.assertEqual(v, mo) self.assertEqual(v, vDatetime(mo)) self.assertEqual(v, vDatetime.from_ical("19870621T035400")) self.assertEqual(v.date(), mo.date()) self.assertEqual(v.time(), mo.time()) self.assertEqual(v.datetime(), timezone.make_aware(mo)) self.assertEqual(v.tzinfo(), None) self.assertEqual(v.zone(), None) self.assertEqual(v.timezone(), pytz.timezone("Asia/Tokyo"))
def testAwareDt(self): mo = vDatetime( timezone.make_aware(dt.datetime(2013, 4, 25, 6, 0), pytz.timezone("Pacific/Chatham"))) v = vDt(mo) self.assertTrue(v) self.assertEqual(v, mo) self.assertEqual(v, mo.dt) self.assertEqual( v, vDatetime.from_ical("20130425T060000", "Pacific/Chatham")) self.assertEqual(v.date(), mo.dt.date()) self.assertEqual(v.time(), mo.dt.time()) self.assertEqual(v.datetime(), mo.dt) self.assertEqual(v.tzinfo(), mo.dt.tzinfo) self.assertEqual(v.zone(), "Pacific/Chatham") self.assertEqual(v.timezone(), pytz.timezone("Pacific/Chatham"))
def ical2xsdt(t): """ Conversion from iCalendar time to xs:dateTime """ # It seems a bit random what type we get here. TODO: Why? if type(t) == list: t = t[0] if type(t) == date: dt = datetime(t.year, t.month, t.day, tzinfo=UTC) elif type(t) != datetime: ical_time = t.ical() dt = vDatetime.from_ical(ical_time) else: dt = t return datetime2xsdt(dt)
def findMonthEvts(self, dayList, listCalendar): #Define the start and end limit start = dayList[0] end = dayList[-1] month_evt={} for n,calendar in enumerate(listCalendar) : if calendar['activate'] == "true" : start_date = '%04d%02d%02d' % (start['year'],start['month'],start['number']) end_date = '%04d%02d%02d' % (end['year'],end['month'],end['number']) print n, calendar if calendar['typeaccount'] == "google" : start_date = '%04d-%02d-%02d' % (start['year'],start['month'],start['number']) end_date = '%04d-%02d-%02d' % (end['year'],end['month'],end['number']) events = self.googleCalendar.return_calendar_events(calendar['login'], calendar['password'], calendar['url'], start_date, end_date) for e in events : month_evt[e] = "event" elif calendar['typeaccount'] == "local" : #Traitment of the local iCalendar File url = translatePath ( calendar['url'] ) cal = Calendar.from_string(open(os.path.join(url),'rb').read()) for evt in cal.walk('VEVENT'): a = '%04d%02d%02d' % (vDatetime.from_ical(evt['dtstart'].ical()).year,vDatetime.from_ical(evt['dtstart'].ical()).month,vDatetime.from_ical(evt['dtstart'].ical()).day) if a >= start_date and a <= end_date: month_evt[a] = "event" elif calendar['typeaccount'] == "web" : pass return month_evt
def get_end_recurrence_datetime(self): if self._recurrence is not None: dt_string = RRuleData(self.get_recurrence()).get('UNTIL') if dt_string: return vDatetime.from_ical(dt_string).\ replace(tzinfo=UTC).astimezone(self.get_timezone())