def ical_view(request): from icalendar import Calendar, Event, Alarm start = date.today().replace(day=1) end = start + timedelta(days=365) cal = Calendar() cal.add('prodid', '-//TogetherCal//%s//HE' % request.META['HTTP_HOST']) cal.add('version', '1.0') cal['dtstart'] = start cal['dtend'] = end for occurrence in Occurrence.objects.filter(date__range=(start, end)).iterator(): e = occurrence.get_event_as_subclass() if not isinstance(e, WeeklyActivity): event = Event() event.add('uid', '%d@%s' % (occurrence.pk, request.META['HTTP_HOST'])) event.add('summary', e.title) event.add('dtstamp', occurrence.date) event.add('class', 'PRIVATE') event.add('categories', occurrence.event_class_name()) alarm = Alarm() alarm.add('action', 'DISPLAY') alarm.add('description', e.title) alarm.add('trigger', timedelta(hours=-1)) event.add_component(alarm) cal.add_component(event) response = HttpResponse(cal.to_ical(), content_type='text/calendar') response['Content-Disposition'] = 'filename="family.ics"' return response
def AddAlarm(event, desc, minutesBefore): alarm = Alarm() alarm.add('action', 'DISPLAY') alarm.add('DESCRIPTION', desc) dur = icalendar.vDuration(datetime.timedelta(0, 0, 0, 0, -minutesBefore)) alarm.add('TRIGGER', dur) event.add_component(alarm)
def addreminder(): form = IcsForm() content = render_template('index.html', form=form) file = form.icsfile.data if not file: return content hours = form.hours.data minutes = form.minutes.data try: calendar = Calendar.from_ical(file.read()) except ValueError: error = 'can\'t read file' return render_template('index.html', form=form, error=error) for component in calendar.walk('VEVENT'): valarm_found = False for k, v in component.property_items(): if k == 'BEGIN' and v == 'VALARM': valarm_found = True if not valarm_found: alarm = Alarm() alarm.add('ACTION', 'DISPLAY') alarm.add('DESCRIPTION', component.get('SUMMARY')) alarm.add('TRIGGER;VALUE=DURATION', '-PT%dH%dM' % (hours, minutes)) component.add_component(alarm) new_ics = tempfile.TemporaryFile() new_ics.write(calendar.to_ical()) new_ics.seek(0) new_filename = file.filename.rstrip('.ics') + '_with_reminders' + '.ics' return send_file(new_ics, as_attachment=True, attachment_filename=new_filename)
def _create_event(self, match): """ Creates a calendar event for the given match :paran match: A Match object holding the match data """ # print(self.team_data) # print(team_data) event = Event() event["uid"] = match.id() event["location"] = match.location event.add("priority", 5) event.add("summary", match.summary()) event.add("description", str(match)) event.add("dtstart", match.match_start) event.add("dtend", match.match_end) event.add("dtstamp", datetime.utcnow()) alarm = Alarm() alarm.add("action", "DISPLAY") alarm.add("description", "Reminder") alarm.add("trigger", timedelta(hours=-1)) event.add_component(alarm) return event
def process_xls(filename): wb = xlrd.open_workbook(filename) sheet = wb.sheet_by_index(0) calendar = Calendar() calendar.add('x-wr-calname', 'Schedule for U8 Adv Winter Hockey 2015') for irow in range(sheet.nrows): row = sheet.row(irow) evt_desc = None if row[0].value == "U8 Advanced": evt_desc = row[0].value if row[1].value == "Group 1" or row[1].value == "Group 2": evt_desc = row[1].value if evt_desc is None: continue basedate = xlrd.xldate_as_tuple(row[3].value, wb.datemode) basedt = list(basedate[:3]) + get_hhmm(row[4].value) tstamp = datetime(*basedt) basedt_end = list(basedate[:3]) + get_hhmm(row[5].value) tstamp_end = datetime(*basedt_end) uid = tstamp.strftime('%Y%m%d%H%M') + '@pugswald.com' event = Event() event.add('uid', uid) event.add('dtstart', tstamp) event.add('summary', 'AYHL Hockey - %s' % evt_desc) event.add('dtend', tstamp_end) event.add('location', row[6].value) alarm = Alarm() alarm.add('action', 'DISPLAY') alarm.add('description', 'Reminder') alarm.add('trigger', timedelta(minutes=-45)) event.add_component(alarm) calendar.add_component(event) print calendar.to_ical()
def writeICS(format_time_list, row): f_year = int(format_time_list[0]) f_month = int(format_time_list[1]) f_day = int(format_time_list[2]) # Event Docs: # https://www.kanzaki.com/docs/ical/ event = Event() alarm = Alarm() alarm.add("description", "This is an event reminder") alarm.add("action", "DISPLAY") alarm.add("trigger", timedelta(minutes=-10)) event.add("rrule", {"freq": "yearly"}) event.add("summary", row["Name"]) event.add("dtstart", datetime(f_year, f_month, f_day, alert_begin, 0, 0, tzinfo=UTC)) event.add("dtend", datetime(f_year, f_month, f_day, alert_end, 0, 0, tzinfo=UTC)) event.add("dtstamp", datetime.now()) # unique ID event["uid"] = str( datetime(f_year, f_month, f_day, alert_begin, 0, 0, tzinfo=UTC)) + row["Name"] event.add("priority", 5) event.add_component(alarm) cal.add_component(event) f = open(ics_export_file, "wb") f.write(cal.to_ical()) f.close()
def write_calendar(summary: str, start: datetime, end: datetime, description: str, location: str, oponent_info: str): calname = "ltc-herren1-" + datetime.strftime(start, "%Y%m%d") + ".ics" t_cal = Calendar() t_cal.add('prodid', '-//LTC Herren 1 Kalender//ltc-scraper.py by Bartosz Swiatek//') t_cal.add('version', '2.0') t_cal.add('method', 'request') event = Event() event.add('uid', uuid.uuid4().hex) event.add('summary', summary) event.add('dtstart', start) event.add('dtend', end) event.add('description', description) event.add('last-modified', datetime.now()) event.add('dtstamp', datetime.now()) event.add('location', location) event.add('comment', oponent_info) alarm = Alarm() alarm.add('action', 'DISPLAY') alarm.add('TRIGGER;RELATED=START', '-P1D') alarm.add('description', 'Erinnerung zum Punktspiel') event.add_component(alarm) t_cal.add_component(event) cal.add_component(event) cwd = os.getcwd() f = open(os.path.join(cwd, calname), 'wb') f.write(t_cal.to_ical()) f.close() del alarm del event del t_cal
def callback4(): make_ical_file.config(state="disabled") cal = Calendar() cal.add('prodid', '-//My calendar product//mxm.dk//') cal.add('version', '2.0') event = Event() last_day_date_selected_begin = last_day_date_selected + "/16/30" last_day_date_selected_end = last_day_date_selected + "/17/00" event.add('summary', last_day_selected + ": " + case_var.get()) event.add( 'dtstart', datetime.datetime.strptime(last_day_date_selected_begin, '%m/%d/%Y/%H/%M')) event.add( 'dtend', datetime.datetime.strptime(last_day_date_selected_end, '%m/%d/%Y/%H/%M')) alarm = Alarm() alarm.add("action", "DISPLAY") alarm.add("description", "Reminder") alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(24)) event.add_component(alarm) cal.add_component(event) m = os.path.join(os.path.expanduser('~'), 'Desktop', "Last Day.ics") with open(m, 'wb') as f: f.write(cal.to_ical()) f.close() quit_button = tk.Button(root, text="Quit", command=quit_widget) quit_button.grid(row=21, column=1)
def process_xls(filename): wb = xlrd.open_workbook(filename) sheet = wb.sheet_by_index(0) calendar = Calendar() calendar.add('x-wr-calname', 'Schedule for U8 Summer Hockey 2015') for irow in range(sheet.nrows): row = sheet.row(irow) basedate = xlrd.xldate_as_tuple(row[1].value, wb.datemode) (hh, mmxx) = row[3].value.split(':') hh = int(hh) mm = int(mmxx[:2]) xx = mmxx[2:] if xx == 'PM': hh += 12 basedt = list(basedate[:3]) + [hh, mm] tstamp = datetime(*basedt) uid = tstamp.strftime('%Y%m%d%H%M') + '@pugswald.com' event = Event() event.add('uid', uid) event.add('dtstart', tstamp) event.add('summary', 'AYHL U8 Hockey %s' % row[2].value) event.add('dtend', tstamp + timedelta(minutes=60)) event.add('location', row[5].value) alarm = Alarm() alarm.add('action', 'DISPLAY') alarm.add('description', 'Reminder') alarm.add('trigger', timedelta(minutes=-45)) event.add_component(alarm) calendar.add_component(event) print calendar.to_ical()
def __add_event(name, times, location, teacher, student_id): event = Event() event.add('transp', 'TRANSPARENT') summary = name if location != 'None': summary = name + '@' + location event.add('location', location) description = times[4] + times[5] if teacher != 'None': description += '\n教师:' + teacher + '\n' description += '由 EveryClass (http://every.admirable.one) 导入' event.add('summary', summary) event.add('description', description) event.add('dtstart', times[0]) event.add('dtend', times[1]) event.add('last-modified', datetime.now()) event['uid'] = 'ec-CSU' + student_id + 't' + datetime.now().strftime( '%y%m%d%H%M%S%f') + '@admirable.one' event.add('rrule', { 'freq': 'weekly', 'interval': times[2], 'until': times[3] }) alarm = Alarm() alarm.add('action', 'none') alarm.add('trigger', datetime(1980, 1, 1, 3, 5, 0)) event.add_component(alarm) return event
def computeIcsCalendar(P, ics_file_name): P.ics_calendar = Calendar() for d in range(1, MAX_SZ - 1): [y, m, dt, t] = swe.revjul(P.jd_start + d - 1) if len(P.festivals[d]) > 0: # Eliminate repeat festivals on the same day, and keep the list arbitrarily sorted P.festivals[d] = sorted(list(set(P.festivals[d]))) summary_text = P.festivals[d] # this will work whether we have one or more events on the same day for stext in summary_text: if not stext.find('>>') == -1: # It's an event, with a start and end time event = Event() [stext, t1, arrow, t2] = stext.split('|') event.add('summary', stext.split('|')[-1].replace('-', ' ').strip()) h1, m1 = t1.split(':') h2, m2 = t2.split(':') event.add( 'dtstart', datetime(y, m, dt, int(h1), int(m1), tzinfo=tz(P.city.timezone))) event.add( 'dtend', datetime(y, m, dt, int(h2), int(m2), tzinfo=tz(P.city.timezone))) P.ics_calendar.add_component(event) else: event = Event() # summary = re.sub('{(.*)}','\\1', ) # strip braces around numbers event.add('summary', stext.replace('-', ' ')) event.add('dtstart', date(y, m, dt)) event.add('dtend', (datetime(y, m, dt) + timedelta(1)).date()) alarm = Alarm() alarm.add('action', 'DISPLAY') alarm.add('trigger', timedelta(hours=-4)) event.add_component(alarm) event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 'TRUE' event['TRANSP'] = 'TRANSPARENT' event['X-MICROSOFT-CDO-BUSYSTATUS'] = 'FREE' P.ics_calendar.add_component(event) if m == 12 and dt == 31: break with open(ics_file_name, 'wb') as ics_calendar_file: ics_calendar_file.write(P.ics_calendar.to_ical())
def create_alarm(message, relative_timedelta): alarm = Alarm() alarm.add('ACTION', 'DISPLAY') alarm.add('DESCRIPTION', message) #print(relative_timedelta); alarm.add('TRIGGER', relative_timedelta, parameters={'VALUE':'DURATION'}) return alarm
def session_ical(session): event = Event() event.add('summary', session.title) event.add( 'uid', "/".join([session.proposal_space.name, session.url_name]) + '@' + request.host) event.add( 'dtstart', utc.localize(session.start).astimezone( timezone(session.proposal_space.timezone))) event.add( 'dtend', utc.localize(session.end).astimezone( timezone(session.proposal_space.timezone))) event.add( 'dtstamp', utc.localize(datetime.now()).astimezone( timezone(session.proposal_space.timezone))) event.add( 'created', utc.localize(session.created_at).astimezone( timezone(session.proposal_space.timezone))) event.add( 'last-modified', utc.localize(session.updated_at).astimezone( timezone(session.proposal_space.timezone))) if session.venue_room: location = [ session.venue_room.title + " - " + session.venue_room.venue.title ] if session.venue_room.venue.city: location.append(session.venue_room.venue.city) if session.venue_room.venue.country: location[len(location) - 1] += ", " + session.venue_room.venue.country else: location.append(session.venue_room.venue.country) event.add('location', "\n".join(location)) if session.venue_room.venue.latitude and session.venue_room.venue.longitude: event.add('geo', (session.venue_room.venue.latitude, session.venue_room.venue.longitude)) if session.description_text: event.add('description', session.description_text) if session.proposal: event.add('url', session.url_for(_external=True)) if session.proposal.section: event.add('categories', [session.proposal.section.title]) alarm = Alarm() alarm.add('trigger', timedelta(minutes=-5)) alarm.add('action', 'display') desc = session.title if session.venue_room: desc += " in " + session.venue_room.title desc += " in 5 minutes" alarm.add('description', desc) event.add_component(alarm) return event
def get_alarm(description, minutes): """ Get an Alarm object with description displayed :param description: description stirng :param minutes: the minutes before the event (int) :return: an alarm object """ alarm = Alarm() alarm['trigger'] = '-PT{}M'.format(minutes) alarm['action'] = 'DISPLAY' alarm['description'] = description return alarm
def check_login_response(self, response): self.log('Add reminder') gcal = Calendar.from_ical(response.body) for component in gcal.walk(): if component.name == "VEVENT": a = Alarm({ 'ACTION': 'DISPLAY', 'TRIGGER;VALUE=DURATION': '-PT15M' }) component.add_component(a) b = Alarm({ 'ACTION': 'DISPLAY', 'TRIGGER;VALUE=DURATION': 'PT0S' }) component.add_component(b) self.log('Save to file') f = open('calendar.ics', 'wb') f.write(gcal.to_ical()) f.close()
def json2ical(sdata): """ Convert epresence conferences sdata: conference list in json format (returned from fetch_conf_list) returns a string, the iCal, to be written to a file e.g. """ import json from icalendar import Calendar, Event, Alarm from datetime import datetime import pytz data = json.loads(sdata) if data: cal = Calendar() cal.add('prodid', '-//Gamisterous epresence ical generator//lala.la//') cal.add('version', '3.0') cal.add('X-WR-CALNAME', 'Τηλεδιασκέψεις') local = pytz.timezone("Europe/Athens") for dato in data: confid = dato["cellID"] desc = dato["cellDesc"] start = datetime.strptime( dato["cellStartDate"] + "-" + dato["cellStartTime"], "%d-%m-%Y-%H:%M") end = datetime.strptime( dato["cellStartDate"] + "-" + dato["cellEndTime"], "%d-%m-%Y-%H:%M") now = datetime.now() event = Event() event.add('SUMMARY', desc) event.add('DTSTART', local.localize(start)) event.add('DURATION', end - start) event.add('DTEND', local.localize(end)) event.add('DTSTAMP', datetime.now()) event.add('URL', 'https://new.epresence.grnet.gr') event['UID'] = "conf" + confid + "@conferences" # add a reminder 30m earlier alarm = Alarm() alarm.add("action", "DISPLAY") alarm.add('description', "Reminder") alarm.add("TRIGGER;RELATED=START", "-PT30M") event.add_component(alarm) cal.add_component(event) return cal.to_ical()
def generate_event(subject: str, payment_date: datetime.date) -> Event: evt = Event() evt.add("summary", subject) notification_time = datetime.time(11, 0) payment_datetime = datetime.datetime.combine(payment_date, notification_time) evt.add("dtstart", payment_datetime) evt.add("dtend", payment_datetime + datetime.timedelta(hours=1)) evt.add("dtstamp", datetime.datetime.now()) alarm = Alarm() alarm.add("trigger", datetime.timedelta(minutes=0)) evt.add_component(alarm) return evt
def toiCalendar(List_Event): # Entry value has the following structure: it is a LIST!!! # [ event = {'name': '', # 'dstart': '' # 'dtend': '' # 'category': "All day event", # 'infoLink': "", # 'ticketsLink': "", # 'image': ""} # ] cal = Calendar() cal.add('prodid', '-//O2 Arena calendar') cal.add('version', '2.0') organizer = vCalAddress('MAILTO:[email protected]') location = vText('O2 Arena at Ceskomoravska') dtstamp = datetime(2017, 10, 24, 0, 0, 0, tzinfo=pytz.utc) for i in (range(len(List_Event))): event = Event() description = "" print("Elem %i and name %s and datestart %s" % (i, List_Event[i]['name'], List_Event[i]['dtstart'])) # print(List_Event[i]) event.add('dtstart', List_Event[i]['dtstart']) event.add('dtend', List_Event[i]['dtend']) event.add('summary', List_Event[i]['name']) event.add('location', location) event.add('organizer', organizer) event.add('url', List_Event[i]['infoLink']) event.add('geo', '50.104788;14.493774') event.add('dtstamp', dtstamp) event['uid'] = ("%s/%[email protected]" % (dtstamp.now().strftime("%Y%m%d%H%M%S"), i)) print(event['uid']) # if there are NOT tickets left. if (List_Event[i]['TicketsLeft'] == 0): alarm = Alarm() alarm.add("action", "DISPLAY") alarm.add("description", "Reminder") alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(1)) description = "This event is FULL! " event.add_component(alarm) # print(event) event.add('description', description + List_Event[i]['description']) cal.add_component(event) # print(event) cal_content = cal.to_ical() with open("O2ArenaCalendar.ics", 'wb') as f: f.write(cal_content)
def genCalendarFromEventsFile(events_file, cal_file): try: events = SimpleEvents(events_file) cal = Calendar() cal.add('prodid', '-//calgen.py//xmpp.org//') cal.add('version', '2.0') day = timedelta(days=1) for ev in events.getEventList(): event = Event() if "date" in ev: ev["date"] = ev["date"].rstrip("Z") if "all-day" in ev: start = datetime.strptime(ev["date"], "%Y-%m-%d") # T%H:%M:%S event.add('dtstart', start.date()) event.add('dtend', (start + day).date()) event.add("dtstamp", (start + day).date()) else: start = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S") start = start.replace(tzinfo=UTC) duration = timedelta(minutes=int(ev["duration"])) event.add('dtstart', start) event.add('dtend', (start + duration)) event.add("dtstamp", (start + duration)) if "alarm" in ev: alarm = Alarm() alarm_time = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S") alarm_time = alarm_time.replace(tzinfo=UTC) alarm_time = alarm_time - timedelta(minutes=15) alarm.add("trigger", alarm_time) alarm.add("action", "display") event.add_component(alarm) if "summary" in ev: event.add('summary', ev["summary"]) if "description" in ev: event.add('description', ev["description"]) if "url" in ev: event.add('url', ev["url"]) cal.add_component(event) allevents.append(event) f = open(cal_file, 'wb') f.write(cal.as_string()) f.close() except: print "File not found! - " + events_file print "Unexpected error:", sys.exc_info()[0] traceback.print_exc(file=sys.stdout)
def html_to_ical(html_string): """Convert an html string from the pointstreak website to ical format Args: html_string - String representing the entire pointstreak schedule page Returns: Calendar object representing schedule """ tree = html.fromstring(html_string) team = tree.xpath("//title")[0].text_content().split('-')[0].strip() schedule_tables = tree.xpath("//table/tr/td[contains(.,'Team Schedule')]") # First match is the table that contains all tables, second is the header in a td schedule_table = schedule_tables[1].getparent().getparent().getnext() # Get home v away, date, time, rink now = datetime.now() calendar = Calendar() calendar.add('x-wr-calname', 'Schedule for %s' % (team)) for row in schedule_table.iter('tr'): try: #print etree.tostring(row) rink = row[4].text_content() if rink.startswith('final'): # Game is already played continue rink = rink.strip() home = row[0].text_content() away = row[1].text_content() date_str = ' '.join( [row[2].text_content(), row[3].text_content(), str(now.year)]) tstamp = datetime.strptime(date_str, "%a, %b %d %I:%M %p %Y") # For whatever reason, the year is never printed if tstamp < now: tstamp.replace(year=tstamp.year + 1) uid = tstamp.strftime('%Y%m%d%H%M') + '@pugswald.com' event = Event() event.add('uid', uid) event.add('dtstart', tstamp) event.add('summary', 'Hockey game %s vs %s' % (home, away)) event.add('dtend', tstamp + timedelta(minutes=90)) event.add('location', rink) alarm = Alarm() alarm.add('action', 'AUDIO') alarm.add('trigger', timedelta(minutes=-60)) event.add_component(alarm) calendar.add_component(event) except: #print sys.exc_info() pass # This block is not good data return calendar
def create_event(self, summary, description, start): """Create a 30 minute calendar event without a reminder""" event = Event() no_alarm = Alarm() event.add('summary', summary) event.add('description', description) event.add('dtstart', start) event.add('dtend', start + relativedelta(minutes=30)) event.add('dtstamp', start) # event.add('location', location) no_alarm.add('action', 'NONE') no_alarm.add('trigger', start - relativedelta( years=1)) # Set an alarm date before the event to remove reminder event.add_component(no_alarm) self.cal.add_component(event)
def create_alarm(diff: timedelta, related: str) -> Alarm: """ Return a new alarm Args: diff (timedelta): The delta between the alarm and the start/end of the event related (str): Is the delta related to the START or the END of the event Returns: Alarm: The Alarm itself """ alarm = Alarm() alarm.add('ACTION', 'DISPLAY') alarm.add('TRIGGER', diff, parameters={'RELATED': related}) return alarm
def create_timetable_ical(semester: Semester, lectures: List[Lecture], language: str): is_english = language and ("en" in language) timezone = pytz.timezone("Asia/Seoul") calendar = Calendar() calendar.add("prodid", "-//SPARCS//OTL Plus//") calendar.add("version", "2.0") calendar.add("x-wr-timezone", timezone) title = f"[OTL] {semester.get_name(language='en').title()}" calendar.add("summary", title) calendar.add("x-wr-calname", title) for l in lectures: for ct in l.classtimes.all(): event = Event() event.add("summary", l.title if not is_english else l.title_en) event.add( "location", ct.get_classroom_strs()[2] if not is_english else ct.get_classroom_strs()[3]) days_ahead = ct.day - semester.beginning.weekday() if days_ahead < 0: days_ahead += 7 first_class_date = semester.beginning + datetime.timedelta( days=days_ahead) event.add( "dtstart", datetime.datetime.combine(first_class_date, ct.begin, timezone)) event.add( "dtend", datetime.datetime.combine(first_class_date, ct.end, timezone)) event.add("rrule", {"freq": "weekly", "until": semester.end}) alarm = Alarm() alarm.add("action", "DISPLAY") alarm.add("trigger", datetime.timedelta(minutes=-15)) event.add_component(alarm) calendar.add_component(event) return calendar
def gen_ical(packet): cal = Calendar() cal['version'] = '2.0' cal['prodid'] = '-//Zhejiang University//LIU Gengming+Chen Yuan//ZH' # *mandatory elements* where the prodid can be changed, see RFC 5445 courses = packet[0] exams = packet[1] for course in courses: for lesson in course['lessons']: weeks = lesson['weeks'] for recur in weeks: event = Event() event.add('summary', unify_brackets(course['name'])) offset_days = lesson['day'] - 1 + 7 * (int(recur) - 1) offset = timedelta(days=offset_days) classdate = week_start + offset start = lesson_time[lesson['start']]['start'] end = lesson_time[lesson['end']]['end'] event.add('dtstart', datetime.combine(classdate, start)) event.add('dtend', datetime.combine(classdate, end)) event.add('location', lesson['location']) event.add('description', u'教师:' + course['teacher']) event['uid'] = str(uuid1()) + '@ZJU' cal.add_component(event) for exam in exams: event = Event() event.add('summary', unify_brackets(exam['name']) + u' 考试') event.add('dtstart', exam['start']) event.add('dtend', exam['end']) event.add('location', exam['location'] + ' ' + exam['seat']) event.add('description', u'学分:' + exam['credit']) event['uid'] = str(uuid1()) + '@ZJU' alarm = Alarm() alarm.add('action', 'DISPLAY') alarm.add('trigger', timedelta(days=-7)) alarm.add('description', u'距离[%s]考试还有一周时间' % unify_brackets(exam['name'])) alarm['uid'] = str(uuid1()) + '@ZJU' event.add_component(alarm) cal.add_component(event) return cal.to_ical()
def setCalendarEvent(calendar, uid, summary, location, startTime, endTime): event = Event() event.add('UID', uid) event.add('DTSTART;VALUE=DATE', startTime) event.add('DTEND;VALUE=DATE', endTime) event.add('SUMMARY', summary) event.add('SEQUENCE', '0') event.add('DESCRIPTION', '') event.add('LOCATION', location) alarm = Alarm() alarm.add('ACTION', 'NONE') alarm.add('TRIGGER;VALUE=DATE-TIME', '19760401T005545Z') alarm.add('DESCRIPTION', 'This is an event reminder') event.add_component(alarm) calendar.add_component(event)
def __add_event(name, times, location, teacher, student_id, day, time): """ 把 `Event` 对象添加到 `calendar` 对象中 :param name: 课程名 :param times: 开始和结束时间 :param location: 课程地点 :param teacher: 任课教师 :param student_id: 学号 :return: `Event` 对象 """ event = Event() event.add('transp', 'TRANSPARENT') summary = name if location != 'None': summary = name + '@' + location event.add('location', location) description = times[4] + times[5] if teacher != 'None': description += '\n教师:' + teacher + '\n' description += '由 EveryClass 每课 (https://everyclass.xyz) 导入' event.add('summary', summary) event.add('description', description) event.add('dtstart', times[0]) event.add('dtend', times[1]) event.add('last-modified', datetime.now()) # day、time、课程名、老师、周次、地点所有元素才能组成一组超码,因此用它们字符串拼接得到的 MD5 作为唯一识别码 event_sk = str(day) + '-' + str( time ) + '-' + name + '-' + teacher + '-' + times[4] + times[5] + '-' + location event['uid'] = hashlib.md5( event_sk.encode('utf-8')).hexdigest() + '@everyclass.xyz' event.add('rrule', { 'freq': 'weekly', 'interval': times[2], 'until': times[3] }) alarm = Alarm() alarm.add('action', 'none') alarm.add('trigger', datetime(1980, 1, 1, 3, 5, 0)) event.add_component(alarm) return event
def __getiCalFromEventlist(self, eventlist, alarm): cal = Calendar() cal.add('prodid', 'libhbtrash') cal.add('version', '0.1') for event in eventlist: icalevent = Event() icalevent.add('dtstart', event[0]) icalevent.add('dtend', event[0] + timedelta(days=1)) icalevent.add('summary', str(event[1])) if alarm != '': alarmtime = timedelta(minutes=-int(alarm)) icalalarm = Alarm() icalalarm.add('action', 'DISPLAY') icalalarm.add('trigger', alarmtime) icalevent.add_component(icalalarm) cal.add_component(icalevent) cal = cal.to_ical() cal = cal.decode("utf-8") return cal
class XlsxEvent: summary = date_start = date_end = location = '' DATE_FORMAT = '%Y-%m-%d %H:%M:%S' ALARM = Alarm() ALARM.add('action', 'display') ALARM.add('trigger', datetime.timedelta(minutes=-30)) def __init__(self, header, row): for i, cell in enumerate(row): field = constants.get(header[i]) if field: setattr(self, field, cell.value) self.validate() self.set_values() def set_values(self): self.location = self.stadium self.summary = '%s - %s' % (self.home, self.away) self.date_start = datetime.datetime.combine(self.date, self.time) self.date_end = self.date_start + datetime.timedelta(hours=2) def __str__(self): return '%s - %s - %s - %s' % ( self.summary, self.date_start, self.date_end, self.location, ) def get_ical_event(self): event = Event() event.add('summary', self.summary) event.add('dtstart', self.date_start) event.add('dtend', self.date_end) event['location'] = self.location event.add('status', 'TENTATIVE') event.add_component(self.ALARM) return event def validate(self): # We should have all constants now assert all([hasattr(self, field) for field in constants.values()])
def getEvent(self): event = Event() alarm = Alarm() alarm.add('UID', uuid.uuid4()) alarm.add('TRIGGER', timedelta(minutes=-15)) alarm.add('ACTION', 'AUDIO') event.add('summary', self.c_name) event.add('dtstart', self.getStartTime(self.time_zone)) event.add('dtend', self.getEndTime(self.time_zone)) event.add('dtstamp', datetime.now(tz=utc)) event.add('location', self.classroom + ' ' + self.c_teacher) event['uid'] = str(uuid.uuid4()) event.add( 'rrule', { 'freq': 'weekly', 'interval': str(self.step), 'count': str(self.end_week - self.start_week + 1) }) event.add('description', self.getDescription()) event.add_component(alarm) return event
def create_simple_event(basedate): event = Event() event.add('summary', 'Simple event') event.add('description', 'This is a simple meeting generated by an awesome script') event.add('uid', "simple-event-1") event.add('location', "Delft") start = basedate.replace(hour=12, minute=0) end = start + timedelta(hours=1) event.add('dtstart', start) event.add('dtend', end) event.add('dtstamp', basedate) alarm = Alarm() alarm.add('trigger', timedelta(minutes=-5)) alarm.add('action', 'display') alarm.add('description', 'meeting coming up in 5 minutes') event.add_component(alarm) return event