def matrix_to_ics(matrix_dict, group, begin, end, directory): c = Calendar() day, month, year = begin.split(" ") begin = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day), MONTHS[month], year) day, month, year = end.split(" ") end = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day), MONTHS[month], year) begin = arrow.get("{} {}".format(begin, HOURS[0]), 'DD MM YYYY HH:mm') end = arrow.get("{} {}".format(end, HOURS[-1]), 'DD MM YYYY HH:mm') # for each day of the week for i, day in enumerate(matrix_dict[group]): # for each course of the day for j, course in enumerate(day): if course: # get begin hour hour = int(HOURS[j].split(':')[0]) minute = int(HOURS[j].split(':')[1]) e = Event() e.name = course e.begin = begin.replace(hour=hour, minute=minute) e.end = e.begin.replace(hours=+1) c.events.append(e) while (e.begin <= end): e = e.clone() e.end = e.end.replace(days=+7) e.begin = e.begin.replace(days=+7) e.uid = uid_gen() c.events.append(e) # next day begin = begin.replace(days=+1) holidays = convert_holidays() for event in c.events: for date in holidays: if str(event.begin.date()) == str(date): c.events.remove(event) if not os.path.exists("ics/" + directory): os.makedirs("ics/" + directory) with open('ics/{}/{}.ics'.format(directory, group), 'w') as f: f.writelines(c)
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 build_ical(lent_list): """Builds ical from a lent list. It takes a lent list that ran through a Marshmallow scheme. :param lent_list: Marshmallowed lent list. :type lent_list: dict :return: ical. :rtype: str """ cal = Calendar() item_dict = defaultdict(list) for i in lent_list['items']: item_dict[i['due_date']].append('{}: {}'.format(i['author'], i['title'])) for k, v in item_dict.items(): event = Event() event.begin = '{} 00:00:00'.format(k) items = '\n'.join(v) event.description = items event.name = 'Bibliotheksrueckgaben: {}'.format(len(v)) cal.events.append(event) return cal
def hook_default_time(task): """ Create ics file based on task data. """ command = get_command(sys.argv) delete = command in ('delete', 'done') if task['due'] and delete: ics_path = os.path.join(CALENDAR, task['uuid'] + '.ics') if os.path.exists(ics_path): os.remove(ics_path) print('Removed task from taskwarrior calendar.') if task['due'] and not delete: cal = Calendar() event = Event() event.name = task['description'] event.begin = task['due'] cal.events.add(event) ics_path = os.path.join(CALENDAR, task['uuid'] + '.ics') if not os.path.exists(CALENDAR): os.makedirs(CALENDAR) with open(ics_path, 'w') as ics_file: ics_file.writelines(cal) print('Updated taskwarrior calendar.')
def json2ics(inputfile): """ convert json containing tuebix 2016 papers to ics """ cal = Calendar() with open(inputfile) as data_file: data = json.load(data_file) next120 = datetime(2016, 5, 1, 8, 0) next55 = datetime(2016, 5, 4, 8, 0) next25 = datetime(2016, 5, 7, 10, 0) for talk in data: event = Event() event.name = talk["titel"] event.description = talk["name"] + "\n" + talk["inhalt"] # keep Ingo out and use him as a Joker at the end if talk["type"]["workshop"] and talk["name"] != "Ingo Blechschmidt": event.begin = next120 event.end = next120 + timedelta(hours=2) next120 += timedelta(hours=2) if next120.hour > 15: next120 += timedelta(hours=16) cal.events.append(event) for cfptype, possible in talk["type"].items(): if possible and cfptype != "workshop": event.name += " ### " + cfptype elif talk["type"]["v55"] and talk["name"] != "Ingo Blechschmidt": event.begin = next55 event.end = next55 + timedelta(hours=1) next55 += timedelta(hours=1) if next55.hour > 15: next55 += timedelta(hours=16) cal.events.append(event) for cfptype, possible in talk["type"].items(): if possible and cfptype != "v55": event.name += " ### " + cfptype elif talk["type"]["v25"] and talk["name"] != "Ingo Blechschmidt": event.begin = next25 event.end = next25 + timedelta(minutes=30) next25 += timedelta(minutes=30) if next25.hour > 15: next25 += timedelta(hours=16) cal.events.append(event) for cfptype, possible in talk["type"].items(): if possible and cfptype != "v25": event.name += " ### " + cfptype with open(icsfile, 'w') as my_file: my_file.writelines(cal)
def parseEvents(events, curEvent): c = Calendar() for e in events: event = Event() event.name = e['Subject'] event.begin = e['Start']['DateTime'] event.end = e['End']['DateTime'] if event.begin >= curEvent.startDate and event.end <= curEvent.endDate: c.events.append(event) return c
def get_ical_event(self, e): ical_event = Event() ical_event.name = self.get_facebook_event_property( e, 'name', '[Some Event]') ical_event.begin = self.get_facebook_event_property( e, 'start_time', '') ical_event.end = self.get_facebook_event_property(e, 'end_time', '') ical_event.uid = self.get_facebook_event_property(e, 'id', '') ical_event.url = 'https://www.facebook.com/events/%s' % self.get_facebook_event_property( e, 'id', '') ical_event.description = '%s\n\n%s' % ( ical_event.url, self.get_facebook_event_property(e, 'description', '')) return ical_event
def generate_status_calendar(status_log: List[LogEntry]) -> StringIO: calendar = Calendar() for status, start, duration in status_log: event = Event() event.name = f"User was {status}" event.begin = start.strftime("%Y-%m-%d %H:%M:%S") event.end = (start + duration).strftime("%Y-%m-%d %H:%M:%S") calendar.events.add(event) out = StringIO() out.writelines(calendar) out.seek(0) return out
def generate(self): ''' Generates the ics calendar invite ''' calendar = Calendar() calendar_event = CalendarEvent() calendar_event.begin = self._event.start calendar_event.end = self._event.end calendar_event.name = self._event.name calendar_event.description = self._description() calendar_event.url = self._url() calendar_event.location = self._location() calendar.events.add(calendar_event) return calendar
def addevent(self): self.bigDate = ("2015-" + self.finalisedDate2 + " " + self.finalisedPeriod + ":00") self.bigDate2 = ("2015-" + self.finalisedDate2) c = Calendar() e = Event() e.name = "Practical request from " + self.teacherVar.get() + " on " + self.dateEntry.get() e.begin = arrow.get(self.bigDate, 'YYYY-MM-DD HH:mm:ss') e.description = ("Practical Request from " + self.teacherVar.get() + ". " + self.teacherVar.get() + " has requested the following equipment: " + self.equipment.get("1.0","end-1c").replace("\n", "<br>") + "It is needed during " + self.periodVar.get() + " on " + self.dateEntry.get() + ".") c.events.append(e) print(c.events) with open('reminder.ics', 'w') as my_file: my_file.writelines(c)
def create_ics(data: List[DataItem], filename: str = "calendar"): """ Summary ------- Parsing a list with data objects (DataItem) in a .ics-format and saves it in data/output. Parameter --------- data : list # DataItem-list with events filename : str # .csv-filename (default: calendar) """ c = Calendar() for event in data: # converting start date, end date and time in order to get reccognized by ics-library start_date = datetime(year=int(event.start_datetime.year), month=int(event.start_datetime.month), day=int(event.start_datetime.day), hour=int(event.start_datetime.hour), minute=int(event.start_datetime.minute), second=int( event.start_datetime.second)).astimezone( pytz.timezone('Europe/Berlin')) end_date = datetime(year=int(event.end_datetime.year), month=int(event.end_datetime.month), day=int(event.end_datetime.day), hour=int(event.end_datetime.hour), minute=int(event.end_datetime.minute), second=int(event.end_datetime.second)).astimezone( pytz.timezone('Europe/Berlin')) # Create event and fill with event data e = Event() e.name = event.module e.begin = start_date e.end = end_date e.location = event.location e.description = event.lecturer # Add event to calendar c.events.add(e) # Create .ics-file with open('data/output/' + filename + '.ics', 'w', newline='', encoding='utf-8') as ics_file: ics_file.writelines(c)
def generate_event(event_name="New Event", event_date=datetime.now(), event_duration="1:00", event_description=""): """Generates event object using event elements as parameters""" e = Event() e.name = event_name e.begin = event_date dur = [int(t) for t in event_duration.split(":")] e.duration = timedelta(hours=dur[0], minutes=dur[1]) e.description = event_description print(e) print('------') return e
def calculate_result(self, stamp, **kwargs): logit("[Calendar] GenerateCalendarTask: starting up! - - - - - - - - - -") sessionTypeValue = SessionType.objects.get(name="Race") currentSeason = Season.objects.filter(year=date.today().year) # logit("[Calendar] Current Season: " + str(currentSeason[0].year)) localtz = dateutil.tz.tzlocal() localoffset = localtz.utcoffset(datetime.datetime.now(localtz)) offsetHours = localoffset.total_seconds() / 3600 # logit("[Calendar] Offset: " + str(offsetHours)) calendar = Calendar() calendar.creator = unicode("IndyBot, a product of /r/INDYCAR on Reddit") raceList = Race.objects.filter(season=currentSeason) for i in xrange(len(raceList)): # logit("[Calendar] ----------------------------------------------- ") # logit("[Calendar] " + raceList[i].title) event = Event() event.name = raceList[i].title event.location = raceList[i].course.name event.description = "Coverage on " + raceList[i].channel startTime = False endTime = False raceSession = Session.objects.get(race_id=raceList[i].id, type_id=sessionTypeValue) startTime = raceSession.tvstarttime + timedelta(hours=offsetHours) if raceSession.tvendtime == None: endTime = startTime + timedelta(hours=3) else: endTime = raceSession.tvendtime + timedelta(hours=offsetHours) event.begin = arrow.get(startTime, 'US/Eastern') event.end = arrow.get(endTime, 'US/Eastern') # logit("[Calendar] Start Time: " + str(event.begin.format('YYYY-MM-DD HH:mm:ss ZZ'))) # logit("[Calendar] End Time: " + str(event.end.format('YYYY-MM-DD HH:mm:ss ZZ'))) calendar.events.append(event) with open('static/races.ics', 'w') as f: f.writelines(calendar) logit("[Calendar] Finished.") return 1
def handle_sncf_message(self, message): payload = list(message.walk())[1].get_payload() payload = payload.replace("\r", "").replace("\n", "").replace("=20", "") root = fromstring( quopri.decodestring(payload).decode("latin1").replace( "\t", "").replace("\n", "").replace('\\xa0', ' ')) departure_city, _, arrival_city, _, seat_info, duration, _ = [ r.replace("\xa0", " ") for r in root.xpath( "//table/tr/td/table/tr/td/table/tr/td/span/text()") ] departure_time, train_id, ticket_id, arrival_time = [ r.replace("\xa0", " ") for r in root.xpath( "//table/tr/td/table/tr/td/table/tr/td/span/b/text()") ] departure_date = [ r.replace("\xa0", " ") for r in root.xpath( "//html/body/table/tr/td/table/tr/td/span/text()") ] c = None target_file = os.path.join(self.output_dir, "calendar.ics") if os.path.isfile(target_file): with open(target_file, "r") as f: c = Calendar(f.read()) if c is None: c = Calendar() e = Event() e.name = "%s: %s -> %s [%s]" % (train_id, departure_city, arrival_city, ticket_id) e.begin = dateparser.parse("%s %s CEST" % (departure_date, departure_time), languages=["fr"]) e.end = dateparser.parse("%s %s CEST " % (departure_date, arrival_time), languages=["fr"]) e.location = departure_city e.description = "%s" % seat_info #weird. sometimes it's list, sometime it's set... if type(c.events) is list: c.events.append(e) else: c.events.add(e) with open(target_file, 'w') as f: f.writelines(c)
def get_cal(): # looks at config.json and retrieves cal info from web link load = {} # open cal from url try: with open(config_file) as data: load.update(json.load(data)) except IOError: print("file configs/config.json not found") raise assert 'ics_url' in load url = load['ics_url'] c = Calendar(urlopen(url).read().decode('iso-8859-1')) #add ucl term dates as all day events e = Event() e.name = "First day of Term 1" e.begin = '20160926 00:00:00' #Monday 26 September 2016 e.make_all_day() c.events.append(e) e = Event() e.name = "Last day of Term 1" e.begin = '20161216 00:00:00' #Friday 16 December 2016 e.make_all_day() c.events.append(e) e = Event() e.name = "First day of Term 2" e.begin = '20170109 00:00:00' #Monday 09 January 2017 e.make_all_day() c.events.append(e) e = Event() e.name = "Last day of Term 2" e.begin = '20170324 00:00:00' #Friday 24 March 2017 e.make_all_day() c.events.append(e) e = Event() e.name = "First day of Term 3" e.begin = '20170424 00:00:00' #Monday 24 April 2017 e.make_all_day() c.events.append(e) e = Event() e.name = "Last day of Term 3" e.begin = '20170609 00:00:00' #Friday 09 June 2017 e.make_all_day() c.events.append(e) #save cal # todo cache cal rather than downloading each time #with open('my.ics', 'w') as f: # f.writelines(c) return c
def generate_calendar_event(self, meal, timestamp): event = Event() event.name = meal.meal_name event.begin = timestamp desc = "" for instruction in meal.instructions: desc += "• " + instruction + "\n" event.description = desc self.calendar.events.add(event) print(f"Added event to calendar: {event}")
def get(self, request, pk, format=None): deliver = self.get_object(pk) serializer = serializers.DeliverSerializer(deliver) c = Calendar() e = Event() e.name = deliver.label e.begin = deliver.start e.end = deliver.end c.events.add(e) c.events with open('my.ics', 'w') as f: f.write(str(c)) return Response(serializer.data)
def create_calendar(uri): c = Calendar(creator="rss2cal.py by raivivek") parsed_feed = feedparser.parse(uri) for entry in parsed_feed.entries: e = Event() e.name = entry.title e.begin = arrow.get(entry.ev_startdate) e.end = arrow.get(entry.ev_enddate) e.description = entry.description e.location = entry.ev_location e.url = entry.link e.categories = [entry.category] c.events.add(e) return c
def generate_event(title, start_date, end_date, description=None, location=None): e = Event() e.name = title e.begin = start_date e.end = end_date if description: e.description = description if location: e.location = location return e
def _generate_calendar(self, checkins): """ Supplied with a list of checkin data from the API, generates an ics Calendar object and returns it. """ print("Generating Calendar") user_url = self._get_user_url() c = Calendar() #for checkin in list(checkins)["checkins"]["items"]: for checkin in checkins: try: venue_name = checkin["venue"]["name"] tz_offset = self._get_checkin_timezone(checkin) e = Event() e.name = "@ {}".format(venue_name) e.location = venue_name e.url = "{}/checkin/{}".format(user_url, checkin["id"]) e.uid = "{}@foursquare.com".format(checkin["id"]) e.begin = checkin["createdAt"] e.end = e.begin # Use the 'shout', if any, and the timezone offset in the # description. description = [] if "shout" in checkin and len(checkin["shout"]) > 0: description = [checkin["shout"]] description.append("Timezone offset: {}".format(tz_offset)) e.description = "\n".join(description) # Use the venue_name and the address, if any, for the location. location = venue_name if "location" in checkin["venue"]: loc = checkin["venue"]["location"] if "formattedAddress" in loc and len( loc["formattedAddress"]) > 0: address = ", ".join(loc["formattedAddress"]) location = "{}, {}".format(location, address) e.location = location c.events.add(e) except: print("Error processing {}".format(venue_name)) continue return c
def _generate_calendar(self, checkins): """Supplied with a list of checkin data from the API, generates an ics Calendar object and returns it. Keyword arguments: checkins -- A list of dicts, each one data about a single checkin. """ user = self._get_user() c = Calendar() for checkin in checkins: if "venue" not in checkin: # I had some checkins with no data other than # id, createdAt and source. continue venue_name = checkin["venue"]["name"] tz_offset = self._get_checkin_timezone(checkin) e = Event() e.name = "@ {}".format(venue_name) e.location = venue_name e.url = "{}/checkin/{}".format(user["canonicalUrl"], checkin["id"]) e.uid = "{}@foursquare.com".format(checkin["id"]) e.begin = checkin["createdAt"] # Use the 'shout', if any, and the timezone offset in the # description. description = [] if "shout" in checkin and len(checkin["shout"]) > 0: description = [checkin["shout"]] description.append("Timezone offset: {}".format(tz_offset)) e.description = "\n".join(description) # Use the venue_name and the address, if any, for the location. location = venue_name if "location" in checkin["venue"]: loc = checkin["venue"]["location"] if "formattedAddress" in loc and len(loc["formattedAddress"]) > 0: address = ", ".join(loc["formattedAddress"]) location = "{}, {}".format(location, address) e.location = location c.events.add(e) return c
def create_calendar_file(slot): """From the slot obj, create a cal ics file.""" c = Calendar() e = Event() slot_id = slot.id dog_name = slot.subject.dog_name date = slot.date start = slot.start end = slot.end # Site times are in local time. Calendar ics files in UTC. # During BST that means a 10AM slot start would appear as 11AM in BST # Therefore necessary to convert to local time # TODO this is a quick hack. Fix properly! first_val_start = start.split(':')[0] start = str(int(first_val_start) - 1) + ':' + start.split(':')[1] first_val_end = end.split(':')[0] end = str(int(first_val_end) - 1) + ':' + end.split(':')[1] # check if start in correct format first_val = start.split(':')[0] if len(first_val) == 1: start = '0' + start # check if end in correct format first_val = end.split(':')[0] if len(first_val) == 1: end = '0' + end start_str = date + ' ' + start + ':00' end_str = date + ' ' + end + ':00' e.name = "Dog Booker: " + dog_name e.begin = start_str e.end = end_str e.description = 'Please co-ordinate a dog sitting!' c.events.add(e) dir_path = os.path.join('app', app.config['CALENDAR_PATH']) if not os.path.exists(dir_path): os.mkdir(dir_path) file_path = os.path.join(app.config['CALENDAR_PATH'], str(slot_id) + '.ics') path = os.path.join('app', file_path) with open(path, 'w') as f: f.writelines(c) return file_path
def make_event(title=None, location=None, description=None, begin_date=None, begin_time=None, end_date=None, end_time=None, organizer=None, attendees=[]): if title is None: raise Exception("make_event: a title parameter is required") if begin_date is None: raise Exception("make_event: a begin_date parameter is required") if begin_time is None: raise Exception("make_event: a begin_time parameter is required") if end_date is None: raise Exception("make_event: an end_date parameter is required") if end_time is None: raise Exception("make_event: an end_time parameter is required") c = Calendar() e = Event() if organizer is not None: e.organizer = Organizer(common_name=organizer.name.full(), email=organizer.email) if len(attendees) > 0: e.attendees = [ Attendee(common_name=attendee.name.full(), email=attendee.email) for attendee in attendees ] e.name = str(title) e.begin = as_datetime( begin_date.replace_time(begin_time), timezone='UTC').format_datetime('yyyy-MM-dd hh:mm:ss') e.end = as_datetime(end_date.replace_time(end_time), timezone='UTC').format_datetime('yyyy-MM-dd hh:mm:ss') if location not in (None, ''): e.location = str(location) if description not in (None, ''): e.description = str(description) c.events.add(e) c.events ics_file = DAFile('ics_file') ics_file.set_random_instance_name() ics_file.initialize(filename="event.ics", mimetype="text/calendar") with open(ics_file.path(), 'w') as f: f.write(str(c)) ics_file.commit() return ics_file
def add_to_calendar(request, pk, slug): conference = Conference.objects.get(id=pk) e = Event() c = Calendar() e.name = conference.name e.begin = conference.start_date.isocalendar() e.end = conference.end_date.isocalendar() e.location = conference.venue c.events.add(e) c.creator = conference.organizer.user.username with open('my.ics', 'w') as my_file: my_file.writelines(c) mail_ics_file.delay(file_name='my.ics', to=request.user.email) return redirect('events:conference-detail', pk=pk, slug=slug)
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 BuildCalendar(TimeTable): c = Calendar() for i in range(len(TimeTable)): entry = TimeTable[i] for j in range(len(entry.Dates)): e = Event() date = entry.Dates[j] start = entry.Start end = entry.End e.name = str(entry.Description + " (" + entry.Type + ")") e.begin = GenerateArrow(date, start) e.duration = GenerateArrow(date, end) - GenerateArrow(date, start) e.location = str(entry.Room) e.description = str(entry.Staff) c.events.add(e) return c
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 create_event(name, when, how='mail', receiver=None, message=None, subject=None): """ Method will create event from specified parameters which can be later added to scheduler. """ e = Event() e.name = name e.begin = when e.description = Scheduler.create_description(how, receiver, message, subject) return e
def export_events_ical(events): calendar = Calendar() for event_key in events: event = event_key.get() if event is None: continue e = Event() e.name = event.title e.begin = event.date e.description = event.description e.location = event.location calendar.events.add(e) return str(calendar)
def generate_calendar( ): #Genera el archivo ics con los eventos del calendario de NEO-LMS calendar = Calendar() calendario = retornar_cal() for evento in calendario: event = Event() event.name = evento["name"] event.begin = evento["fecha"] calendar.events.add(event) calendar.events with open('CalendarioNEO.ics', 'w') as mi_archivo: mi_archivo.writelines(calendar) navegador.quit() messagebox.showinfo('Exito', 'Calendario generado!')
def make(parseds, mondays): calendar = Calendar() calendar.creator = "eAUrnik - Fork me on GitHub: https://git.io/JO5Za" for weekIndex in range(0, len(parseds)): parsed = parseds[weekIndex] monday = mondays[weekIndex] durations = [] for duration in parsed[0]: start, end = duration.split(" - ") start_hours, start_minutes = map(int, start.split(":")) end_hours, end_minutes = map(int, end.split(":")) durations.append( ((start_hours, start_minutes), (end_hours, end_minutes))) data = parsed[1] for day_index in range(0, len(data)): day = monday + timedelta(days=day_index) lessons = data[day_index] for lesson_index in range(0, len(lessons)): for lesson in lessons[lesson_index]: title = lesson[0] subtitle = lesson[1] duration = durations[lesson_index] timezone = ZoneInfo("Europe/Ljubljana") start = datetime(day.year, day.month, day.day, duration[0][0], duration[0][1], tzinfo=timezone) end = datetime(day.year, day.month, day.day, duration[1][0], duration[1][1], tzinfo=timezone) event = Event() event.name = title event.location = subtitle event.begin = start event.end = end calendar.events.add(event) return string(calendar)
def bis_cal(team): mt = pytz.timezone('US/Mountain') utc = pytz.utc link, team_name, session = getUrl(team) if link: with requests.Session() as s: url_root = 'http://www.boulderindoorsoccer.com/schedules/' url = url_root + link soup = BeautifulSoup(s.get(url).text) table = soup.find("table", attrs={"class":"scheduleTable"}) c = Calendar() for tr in table.findAll("tr"): good_line = False column = 1 for td in tr.findAll("td"): if good_line == True: if column == 2: home_team = td.text.strip() elif column == 5: away_team = td.text.strip() column += 1 for span in td.findAll("span"): date = span.text[9:-1].strip() if td.text[0].isdigit() and good_line == False: time = td.text good_line = True column += 1 # Create calendar event if good_line: e = Event() e.name = "Soccer: " + home_team + " v.s. " + away_team timestamp = parse(date + " " + time) mt_time = mt.localize(timestamp) e.begin = mt_time#.astimezone(utc) e.duration = timedelta(minutes=50) e.location = "Boulder Indoor Soccer, 3203 Pearl Street, Boulder, CO 80301, United States" c.events.append(e) cname = team_name + ' ' + session + '.ics' with open(cname, 'w') as ics_file: ics_file.writelines(c) print "Calendar succesfully written for {team_name}, {session}: \"{cname}\"".format(**locals()) else: return None
def _get_ical_events(self, courses): events = [] for course in courses: time_range = self._get_all_events_for_course(course) for event_begin in time_range: event = Event() event.name = course["course_name"] event.begin = event_begin event.end = event_begin.replace( hour=course["end_time"].hour, minute=course["end_time"].minute, second=0, year=course["course_year"], ) event.location = f"{course['hall_name']}, {course['campus']}" events.append(event) return events
def send_mail(description, agenda: Agenda): c = Calendar() e = Event() e.name = 'Atendimento Aset Terapias' str_begin = '-'.join(reversed(agenda.date.split('/'))) str_begin = f'{str_begin} {agenda.time}' e.begin = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') + timedelta(hours=3)) e.end = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') + timedelta(hours=4)) e.attendees = [agenda.appointment.customer.email, agenda.therapist.email] e.description = description c.events.add(e) curdir = os.getcwd() with open(f'{curdir}{os.sep}go.ics', 'w') as f: f.writelines(c) with open( f'{curdir}{os.sep}apps{os.sep}agenda{os.sep}email_templates{os.sep}appointment-confirmation.html' ) as templ: body = ''.join(templ.readlines()) body = body.replace('{{nome}}', agenda.appointment.customer.name) body = body.replace('{{nome_terapia}}', agenda.appointment.specialty) body = body.replace('{{nome_terapeuta}}', agenda.therapist.name) body = body.replace('{{data}}', agenda.date) body = body.replace('{{hora}}', agenda.time) body = body.replace('{{api}}', os.getenv("API_ENDPOINT")) body = body.replace('{{calendar}}', agenda.calendar.name) body = body.replace('{{therapist_mail}}', agenda.therapist.email) body = body.replace('{{date}}', agenda.date.replace('/', '-')) body = body.replace('{{hour}}', agenda.time) yag = yagmail.SMTP(os.getenv("EMAIL_SENDER"), os.getenv("EMAIL_PWD")) yag.send( to=agenda.appointment.customer.email, bcc=agenda.therapist.email, subject="Aset Terapias : Confirmação de consulta", contents=body, attachments=[f'{curdir}{os.sep}go.ics'], newline_to_break=False, )
def ical_content(self): c = Calendar() e = Event() e.alarms = [DisplayAlarm(trigger=self.trigger_datetime)] e.name = self.event_title e.description = self.event_description e.location = self.event_location e.begin = self.start_datetime e.end = self.end_datetime c.events.add(e) ics_str = str(c) ics_str = re.sub(r'DTSTAMP\:(\d+)T(\d+)Z', r'DTSTAMP:\1T\2', ics_str) ics_str = re.sub(r'DTEND\:(\d+)T(\d+)Z', r'DTEND;TZID=%s:\1T\2' % self.timezone, ics_str) ics_str = re.sub(r'DTSTART\:(\d+)T(\d+)Z', r'DTSTART;TZID=%s:\1T\2' % self.timezone, ics_str) return ics_str
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 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 writeICS(): conn = sqlite3.connect('xueshu.sqlite3', detect_types=sqlite3.PARSE_DECLTYPES) c = conn.cursor() now = datetime.now() future = now + timedelta(days=60) items = c.execute('select * from xueshu where startdate>=? and startdate<=?', (now.date(), future.date())) c = Calendar() c.creator = 'meelo' for item in items: e = Event() e.name = item[1].replace(' ','') + '【{}】'.format(item[10]) + item[9] # e.begin = arrow.get(item[3], 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=tz.gettz('Asia/Chongqing')) e.begin = arrow.get(item[3], 'YYYY-MM-DD HH:mm:ss').replace(tzinfo='+08:00') e.duration = timedelta(hours=2) e.location = item[4] e.description = item[12] c.events.append(e) # print(c.events) conn.close() with open('xueshu.ics', 'w', encoding='utf-8') as f: f.writelines(c)
def build_calendar(self, stream=None): """ Build calendar from sessions """ cal = Calendar() # Add sessions and dates to lines for week_pos in range(0, self.plan.weeks_nb): week = [] for day_pos in range(0, 7): sessions = [] date = self.plan.calc_date(week_pos, day_pos) # Render sessions using html template for session in self.plan.sessions.filter(week=week_pos, day=day_pos): e = Event() e.name = session.name e.description = session.sport.name + " - " + session.type + "\n" # [TODO] check hour planned for training e.begin = datetime.combine(date, datetime.min.time()) + timedelta(hours=19) if session.distance is not None: e.description += "Distance: %f \n " % session.distance if session.time is not None: e.description += "Duration: %s \n " % session.time e.duration = session.time else: e.duration = timedelta(hours=2) cal.events.append(e) week.append(sessions or "") stream.write(str(cal))
and event['locCode'] != otherevent['locCode']): locode = locode + otherevent['locCode'][-2:-1] ids.append(otherevent['id']) #I wanted to add the tye of lecture to the start of the title, Again this could probably be improved if "[" in event['desc2']: class_name = event['desc2'].split('[') e.name = '[' + class_name[1] + ' ' \ + (class_name[0])[:-2] + ' (' + event['desc1'] + ')' else: class_name = event['desc2'] e.name = class_name + ' (' + event['desc1'] + ')' #That mess of a code is over now, lets just add everything to the event now logging.debug(e.name + ' - ' + locode) e.begin = event['start'] e.end = event['end'] e.description = event.get('teacherName', '') e.location = locode c.events.append(e) #write it all to file icalfile = ical_loc + username + '.ics' open(icalfile, 'w').writelines(c) with open(icalfile, 'r') as file: lines = file.readlines() lines[1] = lines[1] + 'X-WR-CALNAME: ' + student_name \ + ' Uni Timetable\nX-PUBLISHED-TTL:PT12H' with open(icalfile, 'w') as file:
try: for each in range(len(subject)): subject[each] = str(subject[each])[:n.search(str(subject[each])).start()]+"/"+str(subject[each])[n.search(str(subject[each])).end():] except Exception as e: break; for each in subject: subject[num] = each.split("/") num = num + 1 d = datetime.datetime.today() today = datetime.date.today() begindate = [] c = Calendar() num = 0 for r in range(10): num = 0 for i in range(1): for each in subject: e = Event() if(r == 0): juli = abs(int(changeWeekday(each[2]))-1) begindate.append(today + datetime.timedelta(days = juli)) e.name = each[1] e.begin = str(begindate[num]).replace("-","") +" "+changeTimeStart(each[2]) e.end = str(begindate[num]) +changeTimeEnd(each[2]) begindate[num] = begindate[num]+datetime.timedelta(days = 7) num = num + 1 e.location = each[4] c.events.append(e)
def save(self, item): e = Event() e.name = item['title'][0].strip() e.begin = time.strftime('%Y%m%dT%H%M00Z', time.strptime(item['startDate'][0].strip() + ' ' + item['startTime'][0].strip(), "%d-%m-%Y %H:%M")) e.end = time.strftime('%Y%m%dT%H%M00Z',time.strptime(item['startDate'][0].strip() + ' ' + item['endTime'][0].strip(), "%d-%m-%Y %H:%M")) self.c.events.append(e)
# style times in ical format for i in range(len(stime)): stime[i] = stime[i].replace(":", "") + "00" for i in range(len(etime)): etime[i] = etime[i].replace(":", "") + "00" """########################### FILE CREATION ###########################""" output_file = open(output_path + output_filename, 'w+') # LOGIC c = Calendar() e = Event() # ics library stuff, generates the ics format for i in range(len(sesh)): e = Event() e.name = str(sesh[i]) e.description = stype[i] e.begin = date[i] + "T" + stime[i] + "+0100" # "20170906T140000" e.end = date[i] + "T" + etime[i] + "+0100" # "20170906T15000" e.location = loc[i] c.events.append(e) output_file.writelines(c) output_file.close()
def add_event(date, location, my_name): for specific_event in date: # If there is a specified date if specific_event["date"]["start_date"]: if specific_event["date"]["start_date"] != \ specific_event["date"]["end_date"]: print "Error! Unexpected api return! Start date not same as end date!" break start_time = specific_event["date"]["start_time"] end_time = specific_event["date"]["end_time"] format_time = '%H:%M' time_dur = datetime.strptime(end_time, format_time) - \ datetime.strptime(start_time, format_time) if specific_event["location"]["building"] and \ specific_event["location"]["room"]: location_str = str(specific_event["location"]["building"]) \ + " " + str(specific_event["location"]["room"]) else: location_str = " " start_date = specific_event["date"]["start_date"] date_year = term_dates[str(term_num)]["start"].year my_time_zone = timezone('US/Eastern') dt = my_time_zone.localize(datetime(date_year, int(start_date[:2]), int(start_date[-2:]), int(start_time[:2]), int(start_time[-2:]),0,0)) datetime_str_start = arrow.get(dt) new_event = Event() new_event.name = my_name new_event.location = location_str new_event.begin = datetime_str_start new_event.duration = {"hours":time_dur.seconds//3600, "minutes":(time_dur.seconds//60)%60} if datetime_str_start in events_stack: print "Warning! Duplicate event detected! Event: " \ + my_name + " discarded!" else: events_stack.append(datetime_str_start) cal.events.append(new_event) # If there is no specified date (interates through every day in term) else: start_time = specific_event["date"]["start_time"] end_time = specific_event["date"]["end_time"] format_time = '%H:%M' time_dur = datetime.strptime(end_time, format_time) - \ datetime.strptime(start_time, format_time) location_str = str(specific_event["location"]["building"]) \ + " " + str(specific_event["location"]["room"]) start_date = term_dates[str(term_num)]["start"] end_date = term_dates[str(term_num)]["end"] weekdays = specific_event["date"]["weekdays"] counter = 0; date_days = [0,0,0,0,0,0,0] while counter < len(weekdays): if weekdays[counter] == "T": if (counter + 1) != len(weekdays): if weekdays[counter + 1] == "h": date_days[3] = 1 counter += 1 else: date_days[1] = 1 else: date_days[3] = 1 elif weekdays[counter] == "S": date_days[5] = 1 elif weekdays[counter] == "M": date_days[0] = 1 elif weekdays[counter] == "W": date_days[2] = 1 elif weekdays[counter] == "F": date_days[4] = 1 elif weekdays[counter] == "U": date_days[6] = 1 counter += 1 days_in_term = (end_date - start_date).days + 1 for index in range(days_in_term): one_day = timedelta(days = 1) current_date = start_date + one_day * index if date_days[current_date.weekday()] == 1: my_time_zone = timezone('US/Eastern') dt = my_time_zone.localize\ (datetime(current_date.year, current_date.month, current_date.day, int(start_time[:2]), int(start_time[-2:]), 0, 0)) datetime_str_start = arrow.get(dt) new_event = Event() new_event.name = my_name new_event.location = location_str new_event.begin = datetime_str_start new_event.duration = {"hours":time_dur.seconds//3600, "minutes":(time_dur.seconds//60)%60} if datetime_str_start in events_stack: print "Warning! Duplicate event detected! Event: " \ + my_name + " discarded!" else: events_stack.append(datetime_str_start) cal.events.append(new_event) return
game = Game(clean_team(game_match['home']), clean_team(game_match['away']), clean_time(year, month, day, game_match['tod']), ) logging.info('Parsed: %s' % str(game)) games.append(game) # Collect games by team teams = defaultdict(list) # Exhibition Games games.append(Game('Trois-Rivières', 'Ottawa', arrow.get(datetime.datetime(year, 5, 16, 13, 35, 0), 'US/Eastern'))) games.append(Game('Ottawa', 'Trois-Rivières', arrow.get(datetime.datetime(year, 5, 17, 13, 35, 0), 'US/Eastern'))) for g in games: teams[g.home].append(g) teams[g.away].append(g) # Create calendars for team in ical_teams: c = Calendar() for g in teams[team]: e = Event() e.name = g.away if g.home == team else '@ %s' % g.home e.begin = g.time e.duration = {'hours': 3} c.events.append(e) with open('%s.ics' % team, 'w') as ical: ical.writelines(c)
# generate Calendar cal = Calendar() for grow in gwsheet.get_all_records(): if grow["ICSDate"]!="": try: # print "%s | %s | %s " % (grow["DESC"], grow["ICSDate"], grow["ICSTime"]) evt = Event() # evt.name = unicodedata.normalize('NFKD', unicode(grow["DESC"])) # evt.name = "Nombre evento" # evt.name = grow["DESC"].encode('ascii', 'replace') # evt.name = grow["DESC"] evt.name = unidecode(grow['DESC']) evt.location = unidecode(grow['SALA']) (t_begin, t_end) = grow["TIME"].split("-") d_begin = "%sT%s:00%s" % (grow["ICSDate"], t_begin.strip(), utc_offset) evt.begin = d_begin.replace(":","").replace(".","") d_end = "%sT%s:00%s" % (grow["ICSDate"], t_end.strip(), utc_offset) evt.end = d_end.replace(":","").replace(".","") cal.events.append(evt) print "Added %s starting %s ending %s" % (evt.name, d_begin, d_end) # print "Added %s, event %s" % (grow['DESC'],evt) except: print grow raise # END for grow # Write ics file to disk with codecs.open("lacnic27.ics", "w", encoding="utf-8") as fn: fn.writelines(cal) ## END MAIN ###############################################################################
from ics import Calendar from ics import Event c = Calendar e = Event() e.name = "f*****g bitches" e.begin = '20160122 00:00:00' #e.end = '20160122 01:00:00' #c.events.append(e) c.events with open('test.ics','w') as f: f.writelines(c)