def _generate_ics(self): data = self.data if data != None: c = Calendar() days = list(data.keys()) days.sort() for xday in days: day_data = data[xday] title = day_data[0].text_content() week, day = title.split(", ") week = w2n.word_to_num(week.lstrip("Week ")) day = w2n.word_to_num(day.lstrip("Day ")) offset = (week - 1) * 7 + (day) event_day = self.start_date + timedelta(days=offset) event_day = event_day.replace(hour=0, minute=0, second=0, microsecond=0) description = "".join( [str(html.tostring(el)) for el in day_data]) description = tomd.convert(description) e = Event(name="Magoosh {}".format(title), begin=event_day, end=event_day, description=description) e.make_all_day() c.events.add(e) with open(self.out_file, 'w') as f: f.writelines(c) print("File written to {}".format(self.out_file))
def create_birthday_event(uid: str, name: str, birthday_date: datetime) -> Event: """ Create a birthday event with the provided parameters. :param uid: Friend's FB UID :param name: Friend's FB name :param birthday_date: Friend's birthday date :return: Birthday event """ # Initialize birthday_event to a new event birthday_event = Event() birthday_event.uid = uid birthday_event.name = f"{name}'s Birthday" today = datetime.today() # Calculate the year as this year or next year based on if its past # current month or not year = today.year if birthday_date.month >= today.month else ( today + relativedelta(years=1)).year # Pad day, month with leading zeros to 2dp month = '{:02d}'.format(birthday_date.month) day = '{:02d}'.format(birthday_date.day) birthday_event.begin = f'{year}-{month}-{day} 00:00:00' birthday_event.make_all_day() birthday_event.duration = timedelta(days=1) birthday_event.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY')) return birthday_event
def convert_to_ics(event): ev = Event() # name if event['significant'] == 'Nazionale': ev.name = "Sciopero {} Nazionale".format(event['sector']) else: ev.name = "Sciopero {} {} ({})".format(event['sector'], event['region'], event['province']) # date and time ev.begin = convert_format(event['start_date'], event['start_time']) ev.end = convert_format(event['end_date'], event['end_time']) if event['start_time'] == None: ev.make_all_day() # description ev.description = DESCRIPTION.format( get_default(event, 'modality'), get_default(event, 'labor_unions'), get_default(event, 'categories'), get_default(event, 'proclamation_date'), get_default(event, 'date_of_receipt')) return ev
def create_ics(birthday=None, add_alarms=False, schedule_file='./vaccines.csv', ical_file='./vaccines.ics'): if birthday is None: birthday = date.today() else: birthday = parser.parse(birthday) c = Calendar() for v in load_csv(schedule_file): v = v._asdict() target_months = [k for k, v_ in v.items() if k.startswith('M') and v_] total = v[target_months[-1]] for month in target_months: name = v['name'] + f' {v[month]}/{total}' begin = birthday + relativedelta(months=int(month[1:])) if add_alarms: alarms = [DisplayAlarm(trigger=timedelta(hours=1))] else: alarms = None e = Event(name=name, begin=begin, description=v['abbv'], alarms=alarms) e.make_all_day() c.events.add(e) with open(ical_file, 'w') as f: f.writelines(c)
def export_menu_calendar(self): c = Calendar() shopping_list = [] # create calendar event for _, row in self.menu.iterrows(): e = Event() e.name = '[' + row['meal'].capitalize() + '] ' + row['recipe'] t = datetime.datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(hours=2) e.begin = t.strftime("%Y-%m-%d %H:%M:%S") if row['meal'] == 'lunch': e.duration = {"minutes": 30} else: e.duration = {"minutes": 60} try: e.description = '\n'.join(row['ingredients']) + f"\n\n{row['notes']}" shopping_list.append('\n'.join(row['ingredients'])) except TypeError: e.description = "Please fill the ingredientes for this recipe!" shopping_list.append(f"Ingredients for {row['recipe']}") c.events.add(e) e = Event() e.name = "Shopping List" e.begin = self.start_date e.description = '\n'.join(shopping_list) e.make_all_day() c.events.add(e) fname = "menus/menu_{}.ics".format(self.start_date) with open(fname, 'w') as my_file: my_file.writelines(c) os.system(f"open {fname}")
def create_ics(confs, stream): cal = Calendar() """ # For standard compliance cal.add('prodid', '-//NLP CFP DB calendar//xx.url//') cal.add('version', '2.0') """ for name, data in confs.items(): begin = correct_date(data.get('begin', ''), far_future) end = correct_date(data.get('end', ''), far_future) location = data['location'] url = data['url'] for field_name in ('submission', 'notification', 'camera-ready'): add_event(cal, name, location, url, field_name.upper(), field_name, data, far_future) if begin is not None: if end < begin: end = begin # Conference e = Event(name=name, begin=datetime.combine(begin, datetime.min.time()), location=location, url=url) e.make_all_day() e.duration = end - begin + timedelta(days=1) cal.events.add(e) stream.writelines(cal)
def create_event(name, date): e = Event() e.name = name e.begin = date e.make_all_day() return e
def calendar_entry(request, offer_code): try: offer = models.PoolSpotOffer.objects.get(offer_code=offer_code) if offer.pool_spot: c = Calendar() e = Event() e.name = "%s: trip to %s" % (offer.pool_spot.seat, offer.pool_spot.trip.location) e.description = "%s accepted by %s for the %s trip, %s through %s." % ( offer.pool_spot.seat, offer.resolving_user, offer.pool_spot.trip.location, offer.pool_spot.trip.start_date, offer.pool_spot.trip.end_date) e.begin = offer.date.isoformat() e.make_all_day() c.events.append(e) return HttpResponse(str(c), content_type="text/calendar") # For debuggging the ICS file. # return HttpResponse(str(c)) else: return HttpResponse('400 error') except models.PoolSpotOffer.DoesNotExist: return HttpResponse('400 error')
def run(output_file): calendar = Calendar() datenames, missiondatas, descriptions = parse_website() for datename, data, desc in zip(datenames, missiondatas, descriptions): mission = get_mission(datename) location = get_location(data) begin, is_all_day = get_full_launchtime(datename, data) if begin: event = Event() event.begin = begin event.description = desc.text event.name = mission if is_all_day: event.make_all_day() event.location = location event.uid = mission.replace(" ", "") calendar.events.add(event) with open(output_file, "w") as outfile: outfile.writelines(calendar) print(calendar.events) print(len(calendar.events))
def populate_birthdays_calendar(birthdays): """ Populate a birthdays calendar using birthday objects """ c = Calendar() c.scale = 'GREGORIAN' c.method = 'PUBLISH' c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]' c.extra.append( ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)')) c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H')) c.extra.append( ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/')) cur_date = datetime.now() for birthday in birthdays: e = Event() e.uid = birthday.uid e.name = f"{birthday.name}'s Birthday" # Calculate the year as this year or next year based on if its past current month or not # Also pad day, month with leading zeros to 2dp year = cur_date.year if birthday.month >= cur_date.month else ( cur_date + relativedelta(years=1)).year month = '{:02d}'.format(birthday.month) day = '{:02d}'.format(birthday.day) e.begin = f'{year}-{month}-{day} 00:00:00' e.make_all_day() e.duration = timedelta(days=1) e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY')) c.events.add(e) return c
def checkOutput(year, month): if int(month) < 10: month = '0' + month page = requests.get( "http://www.weeia.p.lodz.pl/pliki_strony_kontroler/kalendarz.php?rok=" + year + "&miesiac=" + month) soup = BeautifulSoup(page.content, 'html.parser') events = soup.find_all('a', class_='active') print(events[0]['href']) desc = soup.find_all(class_='InnerBox') print(desc[0].getText()) c = Calendar() for i in range(len(events)): e = Event() e.name = desc[i].getText() if int(events[i].getText()) < 10: e.begin = year + '-' + month + '-0' + events[i].getText( ) + ' 00:00:00' e.make_all_day() else: e.begin = year + '-' + month + '-' + events[i].getText( ) + ' 00:00:00' e.make_all_day() c.events.add(e) filename = year + month + ".ics" with open(filename, 'w') as my_file: my_file.writelines(c) return send_file(filename, as_attachment=True)
def create_calendar(token, enrollment_id, options): file_list = [] if options['academicCal'] or options['careerCal']: academic_calendar = Calendar() career_calendar = Calendar() for sess in get_sessions(token, enrollment_id)['calendarSessions']: e = Event() if (sess['context']['id'] == 1) and options['academicCal']: start_time = datetime.strptime(sess['session']['startTime'], '%Y-%m-%dT%H:%M:%SZ') end_time = datetime.strptime(sess['session']['endTime'], '%Y-%m-%dT%H:%M:%SZ') e.name = str(sess['session']['chapter']) + ': ' + sess['session']['name'] e.transparent = True if options['academicIsTrans'] else False if options['officeHours']: e.begin = start_time - timedelta(minutes=45) e.end = end_time + timedelta(minutes=30) else: e.begin = start_time e.end = end_time academic_calendar.events.add(e) elif (sess['context']['id'] == 2) and options['careerCal']: e.name = sess['session']['name'] e.begin = sess['session']['startTime'] e.end = sess['session']['endTime'] e.transparent = True if options['careerIsTrans'] else False career_calendar.events.add(e) if len(academic_calendar.events) > 0: academic_file_name = str(enrollment_id) + '-academic-calendar' academic_file_name = academic_file_name + '-oh.ics' if options['officeHours'] else academic_file_name + '.ics' file_list.append(academic_file_name) with open('files/' + academic_file_name, 'w') as f: f.writelines(academic_calendar) if len(career_calendar.events) > 0: career_file_name = str(enrollment_id) + '-career-calendar.ics' file_list.append(career_file_name) with open('files/' + career_file_name, 'w') as f: f.writelines(career_calendar) if options['assignmentCal']: assignment_calendar = Calendar() for assignment in get_assignments(token, enrollment_id)['calendarAssignments']: e = Event() if assignment['context']['id'] == 1: e.name = assignment['title'] e.begin = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1) e.end = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1) e.make_all_day() e.transparent = True if options['assignmentsIsTrans'] else False assignment_calendar.events.add(e) assignment_file_name = str(enrollment_id) + '-assignment-calendar.ics' file_list.append(assignment_file_name) with open('files/' + assignment_file_name, 'w') as f: f.writelines(assignment_calendar) return file_list
def populate_birthdays_calendar(birthdays): """ Populate a birthdays calendar using birthday objects """ c = Calendar() c.scale = 'GREGORIAN' c.method = 'PUBLISH' c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]' c.extra.append( ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)')) c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H')) c.extra.append( ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/')) cur_date = datetime.now() backburner = [] rearrange = False logger.info("Saving birthdays to local cache...") with open('birthdays.pkl', 'wb') as pkl_file: pickle.dump(birthdays, pkl_file) logger.info("Saved to cache (src/birthdays.pkl)") for birthday_i in range(0, len(birthdays)): birthday = birthdays[birthday_i] if (birthday.month == 2 and birthday.day == 29): rearrange = True backburner.append(birthday) del birthdays[birthday_i] birthday_i -= 1 continue if rearrange: if not (birthday.month == 2 and birthday.day == 28): birthdays.insert(birthday_i, backburner) rearrange = False birthday_i -= 1 continue e = Event() e.uid = birthday.uid e.name = f"{birthday.name}'s Birthday" # Calculate the year as this year or next year based on if its past current month or not # Also pad day, month with leading zeros to 2dp year = cur_date.year if birthday.month >= cur_date.month else ( cur_date + relativedelta(years=1)).year month = '{:02d}'.format(birthday.month) day = '{:02d}'.format(birthday.day) e.begin = f'{year}-{month}-{day} 00:00:00' e.make_all_day() e.duration = timedelta(days=1) e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY')) c.events.add(e) return c
def generate_event(name, begin, end, description, uid): e = Event() e.name = name e.begin = datetime.strptime(begin, "%Y%m%d") e.end = datetime.strptime(end, "%Y%m%d") + timedelta(days=1) e.description = description e.uid = uid e.make_all_day() return e
def generate(self): c = Calendar() c.scale = 'GREGORIAN' c.method = 'PUBLISH' c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]' c.extra.append( ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)')) c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H')) c.extra.append( ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/')) cur_date = datetime.now() for facebook_user in self.facebook_users: # Don't add extra 's' if name already ends with 's' formatted_username = f"{facebook_user.name}'s" if facebook_user.name[ -1] != 's' else f"{facebook_user.name}'" formatted_username = f'{formatted_username} Birthday' # Set date components day = facebook_user.birthday_day month = facebook_user.birthday_month year = facebook_user.birthday_year # Feb 29 special case: # If event year is not a leap year, use Feb 28 as birthday date instead if facebook_user.birthday_month == 2 and facebook_user.birthday_day == 29 and not calendar.isleap( year): day = 28 # The birth year may not be visible due to privacy settings # In this case, calculate the year as this year or next year based on if its past current month or not if year is None: year = cur_date.year if facebook_user.birthday_month >= cur_date.month else ( cur_date + relativedelta(years=1)).year # Format date components as needed month = f'{month:02}' day = f'{day:02}' # Event meta data e = Event() e.uid = facebook_user.id e.name = formatted_username e.created = cur_date e.description = f'{facebook_user}\n{generate_facebook_profile_url_permalink(facebook_user)}' e.begin = f'{year}-{month}-{day} 00:00:00' e.make_all_day() e.duration = timedelta(days=1) e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY')) c.events.add(e) self.birthday_calendar = c
def add_event(cal, name, location, url, prefix, field_name, data, far_future_date): due_date = correct_date(data.get(field_name, ''), far_future_date) if due_date < far_future_date: e = Event(name='{0}: {1}'.format(prefix, name), begin=datetime.combine(due_date, datetime.min.time()), end=datetime.combine(due_date, datetime.min.time()), location=location, url=url) e.make_all_day() cal.events.add(e)
def to_ics_event(self): ics_event = ICSEvent( name=self.name, begin=self.date, end=self.end_date, uid=self.id, created=self.created, description=self.content, ) if self.is_all_day(): ics_event.make_all_day() return ics_event
def generate_ics_from_data(content): """ Parameter content will be the raw_data parsed in text form, convert that and return in ics format """ dates_dictionary = OrderedDict() # Dictionary with Dates and number of entries for each day dates_dictionary_formatted = OrderedDict() # Same dictionary formatted dates description = list() # Store the description of events happening each day content = content.split('\n') # Split into lines and return a list file_data = filter(None, content) # remove empty items # Parse data into Dates and events date = '' event_num = 0 for x in file_data : # If the last char of a line is a number it is date if x[-1:].isnumeric(): date = x event_num = 0 dates_dictionary.update({date:event_num}) # If the last word is today , that also means it's a date elif x[-7:] == '- Today': date = x[:-7] # String the today part before appending event_num = 0 dates_dictionary.update({date:event_num}) else: event_num += 1 dates_dictionary.update({date:event_num}) description.append(x) # This is a waste type, not a date # Convert dates into needed format # https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior for x, y in dates_dictionary.items(): date = datetime.strptime(x+' '+YEAR, '%A, %B %d %Y') # Strip date formatted_date = date.strftime('%Y%m%d') # Format date from stripped date dates_dictionary_formatted.update({formatted_date:y}) # Format data into ics file c = Calendar() description_for_the_day = '' # Initialize empty description so it can be appended for x, y in dates_dictionary_formatted.items(): e = Event() for i in range(y): description_for_the_day += description.pop(0) description_for_the_day += ', ' description_for_the_day = description_for_the_day[:-2] # Remove the comma at the end description_for_the_day = rreplace(description_for_the_day, ',', ' and', 1) # Replace last comma with an and e.begin = x+' 00:00:00' e.end = x+' 12:00:00' e.make_all_day() # Make the event all day e.description = "Waste Collection day" e.name = description_for_the_day c.events.add(e) description_for_the_day = '' # Reset this del e # Delete event content after appending to the calendar return c # Return the calendar data
def add_to_icalendar(icalendar_object, event): """ Adds the event to the iCalendar string. """ ical_event = Event() ical_event.name = event['summary'] ical_event.begin = event['start']['date'] if 'location' in event: ical_event.location = event['location'] ical_event.make_all_day() ical_event_string = f"{str(ical_event)[:-10]}{event['recurrence'][0]}\n\n{str(ical_event)[-10:]}" icalendar_object += f"{ical_event_string}\n\n" return icalendar_object
def writeICS(self, path): calendar = Calendar() for event in self.Events: e = Event() e.name = self.title +" - " +event.name e.begin = event.date e.make_all_day() calendar.events.add(e) calendar.events with open(path +"/"+ self.title, 'w') as f: f.write(str(calendar)) f.close() return os.path.abspath(path+"\\"+self.title)
def accept(self): event_name = self.newEventName.toPlainText() is_all_day = self.allDayCheckBox.isChecked() location = self.locationName.toPlainText() start_time = self.startDateTimeEdit.dateTime().toPyDateTime() end_time = self.endDateTimeEdit.dateTime().toPyDateTime() if event_name: event = Event(name=event_name, begin=arrow.get(start_time), end=arrow.get(end_time), location=location) if is_all_day: event.make_all_day() self.event_manager.add_event(event) super().accept()
def parse_roadmap(roadmap): logger.info('Parse roadmap') events = [] for release in roadmap['releases']: event = Event() if release['released']: begin_date = datetime.strptime( release['description'].split(' ', 1)[1], '%B %d, %Y') else: begin_date = get_date_from_quarter(release['description']) event.begin = begin_date event.make_all_day() event.name = 'Star Citizen %s release' % release['name'] event.description = generate_description(release['cards']) events.append(event) return events
def get_deadlines(): deadlines = SPREADSHEETS.worksheet("Deadlines").get_all_records() calendar = Calendar() for deadline in deadlines: event = Event() event.name = deadline["title"] event.description = deadline["description"] event.begin = event.begin = date_from_str(deadline["due_date"]) event.make_all_day() calendar.events.add(event) return Response(str(calendar), headers={ "Content-Disposition": "attachment; filename=events.ics", "Content-Type": "text/calendar" })
def create_ics(cal): for cal_type in cal: c = Calendar() for date in cal[cal_type]: e = Event() date_obj = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S') e.begin = date_obj e.name = "Solid Waste Pickup" e.description = cal[cal_type][date] e.transparent = True e.make_all_day() c.events.add(e) filename = cal_type + "_" + date_obj.strftime("%Y") + ".ics" print("Creating ICS for", cal_type, "Filename:", filename) with open(filename, 'w') as f: f.write(str(c))
def termCal(term): term_start = term.split(" - ")[0].strip() term_end = term.split(" - ")[1].strip() start_obj = datetime.datetime.strptime(term_start, '%d %B %Y') end_obj = datetime.datetime.strptime(term_end, '%d %B %Y') term_length = math.ceil((end_obj - start_obj).days / 7) for x in range(0, term_length): print('Week', x + 1, ":", start_obj.date() + datetime.timedelta(days=7 * x)) e = Event() e.name = "Week " + str(x + 1) e.begin = start_obj.date() + datetime.timedelta(days=7 * x) e.make_all_day() c.events.add(e)
def populate_birthdays_calendar(birthdays): """ Populate a birthdays calendar using birthday objects """ c = Calendar() c.scale = 'GREGORIAN' c.method = 'PUBLISH' c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]' c.extra.append( ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)')) c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H')) c.extra.append( ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/')) cur_date = datetime.now() for birthday in birthdays: e = Event() e.uid = birthday.uid e.name = f"{birthday.name}'s Birthday" # Calculate the year as this year or next year based on if its past current month or not # Also pad day, month with leading zeros to 2dp year = cur_date.year if birthday.month >= cur_date.month else ( cur_date + relativedelta(years=1)).year month = '{:02d}'.format(birthday.month) day = '{:02d}'.format(birthday.day) try: e.begin = f'{year}-{month}-{day} 00:00:00' except ValueError as err: # Check if this is due to leap year. If so, move to Feb 28. if birthday.month == 2 and birthday.day == 29: day = '{:02d}'.format(birthday.day - 1) logger.warning( f"{birthday.name}'s birthday landed on a missing leap day. Moving 1 day earlier ({year}-{month}-{day}) instead." ) e.begin = f'{year}-{month}-{day} 00:00:00' else: raise err e.make_all_day() e.duration = timedelta(days=1) e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY')) c.events.add(e) return c
def generate(self): c = Calendar() c.scale = 'GREGORIAN' c.method = 'PUBLISH' c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]' c.extra.append( ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)')) c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H')) c.extra.append( ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/')) cur_date = datetime.now() for facebook_user in self.facebook_users: e = Event() e.uid = facebook_user.id e.created = cur_date # Don't add extra 's' if name already ends with 's' formatted_username = f"{facebook_user.name}'s" if facebook_user.name[ -1] != 's' else f"{facebook_user.name}'" e.name = f"{formatted_username} Birthday" # Calculate the year as this year or next year based on if its past current month or not # Also pad day, month with leading zeros to 2dp year = cur_date.year if facebook_user.birthday_month >= cur_date.month else ( cur_date + relativedelta(years=1)).year # Feb 29 special case: # If event year is not a leap year, use Feb 28 as birthday date instead if facebook_user.birthday_month == 2 and facebook_user.birthday_day == 29 and not calendar.isleap( year): facebook_user.birthday_day = 28 month = '{:02d}'.format(facebook_user.birthday_month) day = '{:02d}'.format(facebook_user.birthday_day) e.begin = f'{year}-{month}-{day} 00:00:00' e.make_all_day() e.duration = timedelta(days=1) e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY')) c.events.add(e) self.birthday_calendar = c
def get_deadline_by_id(id): """ Returns an iCal calendar event that matches the deadline with the specified id. """ deadlines = SPREADSHEETS.worksheet("Deadlines").get_all_records() for deadline in deadlines: if deadline["id"] == id: calendar = Calendar() event = Event() event.name = deadline["title"] event.description = deadline["description"] event.begin = date_from_str(deadline["due_date"]) event.make_all_day() calendar.events.add(event) return Response(str(calendar), headers={ "Content-Disposition": "attachment; filename=events.ics", "Content-Type": "text/calendar" })
def create_ics(sourceCalData, outFile): """ Creates an .ics file for uploading to calendar services """ cal = Calendar() print(f'Writing ICS file \'{outFile}.ics\'... ', flush=True, end='') for data in sourceCalData: event = Event() event.name = data.get('name') event.begin = data.get('date') event.make_all_day() event.description = data.get('description') event.location = 'The Oregon Community 700 NE Dekum St. Portland OR' cal.events.add(event) with open( outFile + '.ics', 'w', newline='' ) as f: # Clover calendar wont read ics with extra carriage returns f.writelines(cal) print('Done') return
def ics_parser(bday_info_tuple, enable_date_swap): # Set calender info. c = Calendar() c.scale = 'GREGORIAN' c.method = 'PUBLISH' c.creator = 'Hardeep Singh Narang @hardeepnarang10' c._unused.append(ContentLine(name='X-WR-CALNAME', params={}, value='Facebook Birthdays Calendar (fb2ics)')) c._unused.append(ContentLine(name='X-PUBLISHED-TTL', params={}, value='PT12H')) c._unused.append(ContentLine(name='X-ORIGINAL-URL', params={}, value='/events/birthdays/')) # Get present date. present_date = datetime.now() # Process and add individual Events to the Calender object. for each_tuple in bday_info_tuple: # Calculate year for next birthday. # Add padding for day and month (2 digits - leading zero). tuple_date = each_tuple[2] year = present_date.year if int(tuple_date[0:tuple_date.index('/')]) >= present_date.month else (present_date + relativedelta(years=1)).year if enable_date_swap: day = '{:02d}'.format(int(tuple_date[0:tuple_date.index('/')])) month = '{:02d}'.format(int(tuple_date[tuple_date.index('/') + 1:])) else: month = '{:02d}'.format(int(tuple_date[0:tuple_date.index('/')])) day = '{:02d}'.format(int(tuple_date[tuple_date.index('/')+1:])) # Create Event object. e = Event() e.uid = each_tuple[0] e.name = f"{each_tuple[1]}'s Birthday!" e.description = "Facebook friend's birthday! Wish them well!" e.begin = f'{year}-{month}-{day} 00:00:00' e.make_all_day() e.duration = timedelta(days=1) e._unused.append(ContentLine(name='RRULE', params={}, value='FREQ=YEARLY')) c.events.add(e) return c