def create_calendar_with_events(start_time, end_time, SUMMARIS, LOCATION): ''' Function to create calendar with events and save them as isc file Arg: datetime list of start dates, datetime list of end dates, string list of summaries, string list of locations ''' cal = Calendar() # init the calendar # Some properties are required to be compliant: cal.add('mothod', 'REQUEST') cal.add('prodid', '-//My calendar product//mxm.dk//') cal.add('version', '2.0') # Loop for creation events using lists with start dates, end dates, summaries and locations: for y in range(len(start_time)): # Convert each start time to start time with timezone without_timezone = start_time[y] timezone = pytz.timezone("UTC") start_time_with_tz = timezone.localize(without_timezone) # Convert end time to end time with timezone without_tz = end_time[y] timezone = pytz.timezone("UTC") end_time_with_tz = timezone.localize(without_tz) # Create events event = Event() event.add('dtstart', start_time_with_tz) event["DTSTART"].params.clear() event.add( 'dtend', end_time_with_tz) # add start date of an event to calendar event event["DTEND"].params.clear() event.add('dtstamp', start_time_with_tz) event["DTSTAMP"].params.clear() event['uid'] = str(y) event.add('summary', SUMMARIS[y]) # add event sumarry to calendar event event.add('location', LOCATION[y]) # add event location to calendar event event.add('priority', 5) cal.add_component(event) # add events to the calendar # Save events as ics file f = open('buene_events.ics', 'wb') f.write(cal.to_ical()) f.close()
def event_generate_ical_for_calendar(request): if request.method == "POST": try: page = CoderedPage.objects.get(id=request.POST.get('page_id')).specific except ValueError: raise Http404 ical = Calendar() for event_page in page.get_index_children(): for e in event_page.specific.create_recurring_ical(): ical.add_component(e) response = HttpResponse(ical.to_ical(), content_type="text/calendar") response['Filename'] = "calendar.ics" response['Content-Disposition'] = 'attachment; filename=calendar.ics' return response raise Http404()
def task_to_cal(config): cal = Calendar() addCalHeaders(cal) reader = TaskListReader(config) while True: try: task = reader.next() addCalEvent(cal, task) except ValueError as ex: print >> sys.stderr, "ValueError reported: %s" % ex continue except StopIteration: break return cal.to_ical()
def generate_calendars(entry_url=ENTRY_URL): calendars = dict() urls = data_urls(entry_url) for url in urls: for region, events in parse_data(url).items(): calendar = calendars.setdefault(region.replace(' ', ''), Calendar()) name = f'Schoolvakanties {region}' calendar['prodid'] = PRODID calendar['version'] = ICAL_VERSION calendar['name'] = name calendar['x-wr-calname'] = name calendar['x-wr-timezone'] = TIMEZONE for event in events: calendar.add_component(event) return calendars
def schedule_ical(project, rsvp=None): cal = Calendar() cal.add('prodid', "-//HasGeek//NONSGML Funnel//EN") cal.add('version', '2.0') cal.add('name', project.title) cal.add('x-wr-calname', project.title) cal.add('summary', project.title) cal.add('description', project.tagline) cal.add('x-wr-caldesc', project.tagline) cal.add('timezone-id', project.timezone.zone) cal.add('x-wr-timezone', project.timezone.zone) cal.add('refresh-interval;value=duration', 'PT12H') cal.add('x-published-ttl', 'PT12H') for session in project.scheduled_sessions: cal.add_component(session_ical(session, rsvp)) return cal.to_ical()
def save_sessions_to_ical(sessions, filename='export.ics'): with open( os.path.join(os.path.dirname(__file__), EXPORTS_FOLDER, filename), 'wb') as output_file: cal = Calendar() for session in sessions: event = Event() event['uid'] = session.id event['summary'] = session.title event['dtstart'] = datetime.strftime(session.start, '%Y%m%dT%H%M%S') event['dtend'] = datetime.strftime(session.end, '%Y%m%dT%H%M%S') event['description'] = session.abstract event['location'] = session.location cal.add_component(event) output_file.write(cal.to_ical())
def export_schedule(self, out_file, flat=False): self._now = datetime.datetime.now() cal = Calendar() cal_params = [('prodid', '-//python-schedules-tools//ICS handler//'), ('version', '2.0'), ('summary', self.schedule.name), ('uid', self.schedule.slug)] [cal.add(k, v) for k, v in cal_params] self.add_tasks_to_calendar(cal, self.schedule.tasks) content = cal.to_ical() with open(out_file, 'wb') as f: f.write(content) return content
def icalendar_from_file(pathname=None, ddecode=False): """load ics file into icalendar object""" if pathname == None: pathname = get_path('work_directory', 'obm_ics') g = open(pathname, 'rb') if ddecode: icaldata = doubledecode(g.read().replace(b'\r', b'')) else: icaldata = g.read() g.close() try: cal = Calendar().from_ical(icaldata) except: print(pathname, ddecode) return (None) return (cal)
def ical(data, path, name): """ creates ical file of data at path """ os.chdir(path) cal = Calendar() for index, row in data.iterrows(): event = Event() event.add('dtstart', row['begin']) event.add('dtend', row['end']) event.add('summary', row['name']) cal.add_component(event) f = open(name + '.ics', 'wb') f.write(cal.to_ical()) f.close()
def __init__(self): self.cal = Calendar() self.cal.add('prodid', '-//My calendar product//mxm.dk//') self.cal.add('version', '2.0') self.current_event = None self.processing_event = False self.current_description = dict(Talks=u"", Papers=u"", Posters=u"", Demos=u"", Chair=u"", Tutorial=u"", Discussion=u"", Keynote=u"") self.uid_control = dict() return
def __init__(self): if not self.__ICS_FILE.exists(): self.__ical = Calendar() self.__ical.add('prodid', '-//TerrariumPI calendar//terrarium.theyosh.nl//') self.__ical.add('version', '2.0') self.__ICS_FILE.write_bytes(self.__ical.to_ical()) self.create_event( None, 'TerrariumPI initial github commit', 'First commit on Github', 'https://github.com/theyosh/TerrariumPI/commit/526d39a9ceac57768c6fffe6ffe19afd71782952', datetime(2016, 1, 14, 0, 0, 0, 0, timezone.utc)) self.__ical = Calendar.from_ical(self.__ICS_FILE.read_bytes())
def journal_add(caldav_conn, args): ## TODO: copied from todo_add, should probably be consolidated cal = Calendar() cal.add('prodid', '-//{author_short}//{product}//{language}'.format(author_short=__author_short__, product=__product__, language=args.language)) cal.add('version', '2.0') journal = Journal() ## TODO: what does the cryptic comment here really mean, and why was the dtstamp commented out? dtstamp is required according to the RFC. ## TODO: (cryptic old comment:) not really correct, and it breaks i.e. with google calendar journal.add('dtstamp', datetime.now()) journal.add('dtstart', date.today()) journal.add('summary', ' '.join(args.summaryline)) uid = uuid.uuid1() journal.add('uid', str(uid)) cal.add_component(journal) _calendar_addics(caldav_conn, cal.to_ical(), uid, args) print("Added journal item with uid=%s" % uid)
def createCalendarData(self, ownerId=None, ownerType=None, permissions=None, data=None): if ownerId is None: logWarning( "NO OWNER ID WAS GIVEN WHEN ATTEMPTING TO LOOK UP CALENDAR") return None if data is None: data = Calendar().to_ical() result = self.DB_BRIDGE.getCalendarFromOwnerId(ownerId) if result is None: result = DBCalendarData() result.setCalendarData(ownerId, ownerType, permissions, data) result.saveToDB() return result
def __init__(self): self.CSV_FILE_LOCATION = None self.SAVE_LOCATION = None self.HEADER_COLUMNS_TO_SKIP = 0 # The variables below refer to the column indexes in the CSV self.NAME = 0 self.START_DATE = 1 self.END_DATE = 1 self.DESCRIPTION = 2 self.LOCATION = 3 self.START_TIME = 0 self.END_TIME = 0 self.csv_data = [] self.cal = Calendar()
def make_calendar(classes): calendar = Calendar() calendar.add('prodid', '-//UNT Schedule Exporter//undercase//') calendar.add('version', '2.0') for period in classes: event = Event() event.add('summary', period[0]) event.add('dtstart', period[1]) event.add('dtend', period[2]) event.add('rrule', {'freq': 'weekly'}) calendar.add_component(event) output = open('UNT_schedule.ics', 'wb') output.write(calendar.to_ical()) output.close()
def ical_view(request, name, date): """ Route that returns an ical file for a specific event. :return: ical file as part of HttpResponse with only the details of a specific event """ event_date = datetime.datetime.strptime(date, '%Y%m%d') name = urllib.parse.unquote_plus(name) cal = Calendar() cal.add('prodid', '-//Calendar Event event//mxm.dk//') cal.add('version', '2.0') event = Event() event.add('summary', name) event.add('dtstart', event_date) cal.add_component(event) return HttpResponse(cal.to_ical(), content_type="text/calendar")
def generate_event_ical(self): from icalendar import Calendar, Event, vText, vCalAddress calendar = Calendar() cevent = Event() if self.start_time: cevent.add('dtstart', self.start_time) if self.end_time: cevent.add('dtend', self.end_time) if self.address: cevent.add('location',vText(self.address)) # organizer = vCalAddress('') # organizer.params['cn']= vText(self.organizer.name) # cevent['organizer']=organizer cevent.add('summary', self.title) calendar.add_component(cevent) return calendar.to_ical()
def toICalEvent(self, event: EventModel): """ Creates a iCal string containing just one event @param event: EventModel @return: str """ cal = Calendar() # add required properties to calendar cal.add('prodid', PRODID) cal.add('version', '2.0') # create ical event ev = Event() # add required properties to event ev.add( 'uid', '{time}-{eventID}@{domain}'.format( time=datetime.utcnow().isoformat(), eventID=event.getID(), domain=ICS_DOMAIN)) ev.add('dtstamp', datetime.utcnow()) startTime = event.getHappeningDate( ) if event.getHappeningTime() is None else event.getHappeningTime() ev.add('dtstart', startTime) # make the event transparent (in order not to block the calendar slot) ev.add('transp', 'TRANSPARENT') # add optional parameters title = event.getTitle() description = event.getDescription() link = event.getLink() categories = event.getCategories() if not title == '': ev.add('summary', title) if not description == '': ev.add('description', description) if not link == '': ev.add('link', link) if not len(categories) == 0: ev.add('categories', [cat.getName() for cat in categories]) cal.add_component(ev) return cal.to_ical()
def render_to_response(self, context): # A hack while waiting for python 1.5 upgrade cal = Calendar() cal.add('version', '2.0') cal.add('prodid', '-//Nidarholm//Publisert kalender//') cal.add('X-WR-CALNAME', 'Publisert kalender') #cal.add('method', 'PUBLISH') #cal.add('calscale').value = 'GREGORIAN' cal['x-original'] = "http://" + self.request.get_host() + reverse( 'events-archive') localtimezone = LocalTimezone() for event in self.get_queryset(): e = CalendarEvent() e['uid'] = "*****@*****.**" % event.id e.add( 'url', "http://" + self.request.get_host() + event.get_absolute_url()) e.add('summary', event.title) e.add('description', event.content) if event.location: e.add('location', event.location) e.add('dtstamp', event.updated.replace(tzinfo=pytz.utc)) if event.whole_day or event.start.time() == time(0, 0, 0): e.add('dtstart', event.start.replace(tzinfo=pytz.utc).date()) if not event.end or event.end == event.start: e.add('dtend', (event.start + timedelta(1)).replace(tzinfo=pytz.utc).date()) else: e.add('dtend', event.end.replace(tzinfo=pytz.utc).date()) else: e.add('dtstart', event.start.replace(tzinfo=pytz.utc)) if event.end: e.add('dtend', event.end.replace(tzinfo=pytz.utc)) else: e.add('dtend', event.start.replace(tzinfo=pytz.utc)) cal.add_component(e) icalstream = cal.to_ical() response = HttpResponse(icalstream, mimetype='text/calendar') name = slugify(self.request.organization.site.name) response['Filename'] = name + '.ics' # IE needs this response[ 'Content-Disposition'] = 'attachment; filename=' + name + '.ics' response['Content-Type'] = 'text/calendar; charset=utf-8' return response
def export_as_ical(event_id): """Takes an event id and returns the event in iCal format""" event = EventModel.query.get(event_id) cal = Calendar() cal.add('prodid', '-//fossasia//open-event//EN') cal.add('version', '2.0') cal.add('x-wr-caldesc', event.name) cal.add('x-wr-calname', "Schedule for sessions at " + event.name) tz = event.timezone or 'UTC' tz = pytz.timezone(tz) sessions = Session.query\ .filter_by(event_id=event_id) \ .filter_by(state='accepted') \ .filter(Session.in_trash is not True) \ .order_by(asc(Session.start_time)).all() for session in sessions: if session and session.start_time and session.end_time: event_component = icalendar.Event() event_component.add('summary', session.title) event_component.add('geo', (event.latitude, event.longitude)) event_component.add( 'location', session.microlocation.name or '' + " " + event.location_name) event_component.add('dtstart', tz.localize(session.start_time)) event_component.add('dtend', tz.localize(session.end_time)) event_component.add('email', event.email) event_component.add('description', session.short_abstract) event_component.add( 'url', url_for('event_detail.display_event_detail_home', identifier=event.identifier, _external=True)) attendees = [] for speaker in session.speakers: attendees.append(speaker.name) event_component.add('attendee', attendees) cal.add_component(event_component) return cal.to_ical()
def make_icalendar_data(uid, summary, current, end, begin, account_id, create_flag=False): """ Generate iCalendar data format message body. reference - https://developers.worksmobile.com/jp/document/1007011?lang=en """ cal = Calendar() cal.add('PRODID', 'Works sample bot Calendar') cal.add('VERSION', '2.0') standard = TimezoneStandard() standard.add('DTSTART', datetime(1970, 1, 1, 0, 0, 0, tzinfo=pytz.timezone(TZone))) standard.add('TZOFFSETFROM', current.utcoffset()) standard.add('TZOFFSETTO', current.utcoffset()) standard.add('TZNAME', current.tzname()) tz = Timezone() tz.add_component(standard) tz.add('TZID', tz) event = Event() event.add('UID', uid) if create_flag: event.add('CREATED', current) event.add('DESCRIPTION', account_id) event.add('SUMMARY', summary) event.add('DTSTART', begin) event.add('DTEND', end) event.add('LAST-MODIFIED', current) event.add('DTSTAMP', current) cal.add_component(event) cal.add_component(tz) schedule_local_string = bytes.decode(cal.to_ical()) LOGGER.info("schedule:%s", schedule_local_string) return schedule_local_string
def genCalInvite(startDate, endDate, organizerName, organizerEmail, attendeeName, attendeeEmail, createdDate, uuidVal, eventTitle, eventDescription): cal = Calendar() cal.add("VERSION", "2.0") cal.add("CALSCALE", "GREGORIAN") cal.add("METHOD", "REQUEST") event = Event() event['dtstart'] = startDate event['dtend'] = endDate event.add('organizer', 'MAILTO:' + organizerEmail, parameters={"CN": organizerName}) event['uid'] = uuidVal event.add('attendee', 'MAILTO:' + attendeeEmail, parameters={ "CUTYPE": "INDIVIDUAL", "ROLE": "REQ-PARTICIPANT", "PARTSTAT": "NEEDS-ACTION", "RSVP": "TRUE", "CN": attendeeName, "X-NUM-GUESTS": "0" }) event.add('attendee', 'MAILTO:' + organizerEmail, parameters={ "CUTYPE": "INDIVIDUAL", "ROLE": "REQ-PARTICIPANT", "PARTSTAT": "NEEDS-ACTION", "RSVP": "TRUE", "CN": organizerName, "X-NUM-GUESTS": "0" }) event.add('created', createdDate) event.add('description', eventDescription) event.add('last-modified', createdDate) event.add('sequence', "0") event.add('status', "CONFIRMED") event.add("summary", eventTitle) event.add("transp", "OPAQUE") event.add("X-APPLE-TRAVEL-ADVISORY-BEHAVIOR", "AUTOMATIC") cal.add_component(event) return cal.to_ical()
def ical2(): cal = Calendar() from datetime import datetime, timedelta cal.add('prodid', '-//My calendar product//mxm.dk//') cal.add('version', '2.0') import pytz ## write here first Monday of the year d1 = datetime(2017, 1, 2, 0, 0, 0, tzinfo=pytz.utc) cph = pytz.timezone('Europe/Copenhagen') #d2.strftime("%A %d. %B %Y") for k in dic: for w in dic[k]: if w <= 13 or w >= 44: offset = 1 else: offset = 2 event = Event() #event.add("CHARSET","UTF-8") event.add( 'summary', crscode + ' ' + dic[k][w][1] + dic[k][w][0][0:2] + ' ' + dic[k][w][3]) setime = dic[k][w][2].split("-") day = dic[k][w][4].encode("UTF-8") dts = timedelta(weeks=w - 1, days=day2num[day.rstrip()], hours=int(setime[0]) - offset) dte = timedelta(weeks=w - 1, days=day2num[day.rstrip()], hours=int(setime[1]) - offset) print k, w, setime, dts, (d1 + dts).astimezone(cph) event.add('dtstart', (d1 + dts).astimezone(cph)) event.add('dtend', (d1 + dte).astimezone(cph)) event.add('dtstamp', datetime.now()) uid = k + ", " + str(w) # '20050115T101010/[email protected]' uid = uid.replace(' ', '_').replace(',', '_') event['uid'] = uid event.add('priority', 1) cal.add_component(event) calfile = sys.argv[2][:-5] + '.ics' print calfile f = open(calfile, 'wb') f.write(cal.to_ical()) f.close()
def ics_file(talks, filename, user=current_user): cal = Calendar() cal.add("VERSION", "2.0") cal.add("PRODID", topdomain()) cal.add("CALSCALE", "GREGORIAN") cal.add("X-WR-CALNAME", topdomain()) for talk in talks: cal.add_component(talk.event(user=user)) bIO = BytesIO() bIO.write(cal.to_ical()) bIO.seek(0) return send_file(bIO, attachment_filename=filename, as_attachment=True, add_etags=False)
def main(): # login req = requests.Session() while not login(req): print(u'login failed') print('正在处理...') course_req_post_data = {'studentNo': username} course_req_result = req.post( url_index + '/StudentQuery/CtrlViewQueryCourseTable', course_req_post_data) soup = BeautifulSoup(course_req_result.text, "html.parser") course_table = soup.table course_trs = course_table.find_all('tr') # init calendar cal = Calendar() cal.add('prodid', 'class') cal.add('version', '2.0') # add events from courses for i in range(3, len(course_trs) - 1): tds = course_trs[i].find_all('td') course_times = string_to_time(tds[6].text) for index, time in enumerate(course_times): event = Event() event.add('summary', tds[2].text.replace("\n", "").strip()) # course name event.add('dtstart', time['start_time']) # course start time event.add('dtend', time['end_time']) # course end time event.add( 'dtstamp', datetime.datetime.now( tz=pytz.timezone('Asia/Shanghai'))) # course edit time event['location'] = vText(tds[7].text.replace( "\n", "").strip()) # course location event['uid'] = vText(tds[1].text.replace("\n", "").strip() + tds[3].text.replace("\n", "").strip() + str(index)) # course id + teacher id cal.add_component(event) # write to ics with open('class_schedule.ics', 'wb') as f: f.write(cal.to_ical()) print('输出成功!请将 `class_schedule.ics` 文件导入到日历。')
def events_to_ical(events, title): cal = Calendar() cal.add('summary', title) cal.add('X-WR-CALNAME', title) cal.add('X-WR-CALDESC', title) cal.add('version', '2.0') for event in events: cal_event = Event() cal_event.add('uid', event.slug) cal_event.add('summary', event.title) cal_event.add('location', event.location + ", " + event.address) cal_event.add('dtstart', event.start_dt) cal_event.add('dtend', event.end_dt) cal.add_component(cal_event) return cal.to_ical(), 200, {'Content-Type': 'text/calendar'}
def write_calendar(options, sources, filename): """Create and write ics file""" cal = Calendar() timezones_cache = [] for key, value in options.items(): cal.add(key, value) for source_id, category in sources.items(): for timezone in in_cals[source_id].walk('VTIMEZONE'): if timezone['tzid'] not in timezones_cache: timezones_cache.append(timezone['tzid']) cal.add_component(timezone) for event in in_cals[source_id].walk('VEVENT'): event_copy = Event(event) event_copy.add('categories', category) cal.add_component(event_copy) with open(filename, 'wb') as f: f.write(cal.to_ical())
def make_ics(course_dict): cal = Calendar() cal.add('version', 3.0) global seme_start_date seme_start_date = course_dict["BeginDate"] event_whole = [] for c in course_dict["Courses"]: event_whole.extend(process_course(c)) for e in event_whole: cal.add_component(e) filename = input("请输入保存的文件名>") with open(f'{filename}.ics', 'wb') as ics: ics.write(cal.to_ical()) print(f"iCalendar日历文件已导出到{filename}.ics中!")
def make_ics(info, type, index): date = info[0].split(" ")[0] time = info[0].split(" ")[1] name, number, id = parse_text(info[1], type) print(name) print(number) print(id) cal = Calendar() event = Event() if type == 3: hour = 21 elif type == 2: hour = 22 else: hour = 23 print(hour) event.add( 'dtstart', datetime(int(date.split("-")[0]), int(date.split("-")[1]), int(date.split("-")[2]), hour, 30, 0, tzinfo=pytz.timezone("Asia/Shanghai"))) event.add( 'dtend', datetime(int(date.split("-")[0]), int(date.split("-")[1]), int(date.split("-")[2]), hour, 59, 0, tzinfo=pytz.timezone("Asia/Shanghai"))) event.add('summary', name + u" " + id + u"号, " + number) event.add('DESCRIPTION', info[1]) cal.add_component(event) filename = 'cal' + str(index) + '.ics' f = open(os.path.join('/tmp', filename), 'wb') f.write(cal.to_ical()) f.close() os.system('open /tmp/' + filename)
def _convert(self): if self.converted: return self._ical = Calendar() self._ical.add('summary', self._get_title()) tz = pytz.timezone(self._get_timezone()) for event in self.events: start_date = event.get('start_date', event['periods'][0]['start']) repeat = event.get('repeat', 1) days = YamlCalConverter.DAYS_OF_WEEK.values() if 'days' in event: days = [ YamlCalConverter.DAYS_OF_WEEK[day] for day in event['days'] ] periods = None if 'periods' in event: periods = list(event['periods']) if len(event['periods']) > 0 \ else None dates = YamlCalConverter.generate_series_datetimes( start_date, periods, event['start_time'], event['end_time'], days, repeat, tz) index_offset = event.get('start_at', 1) total = event.get('out_of', repeat) overrides_unlocalized = event.get('overrides', {}) overrides = {} for key, val in overrides_unlocalized.iteritems(): overrides[tz.localize(key)] = { 'start': tz.localize(val['start']), 'end': tz.localize(val['end']), } for idx, (start, end) in enumerate(dates): times = overrides.get(start, {'start': start, 'end': end}) e = Event() title = event['name'] if self._count_in_title() and total > 1: title += " ({0} of {1})".format(index_offset + idx, total) e.add('summary', title) e.add('description', self._create_description(event, idx + 1)) e.add('location', event['location']['description']) e.add('dtstart', times['start']) e.add('dtend', times['end']) self._ical.add_component(e) self.converted = True