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 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 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 create_lecture_event(lecture): ''' Create the calendar event given the lecture. ''' try: course = [x for x in courses if int(x[FIELD_TEACHING_ID]) == \ lecture[LECTURE_COURSE_ID]][0] # assume there is only one except IndexError as ie: print("Something gone wrong, I can't find the course with this id: {}".format(lecture[LECTURE_COURSE_ID])) exit(2) e = Event() e.name = sub(SUBJECT_REGEX, '', course[FIELD_TEACHING_SUBJECT_DESCRIPTION].capitalize()) if course[FIELD_TEACHING_TEACHER_NAME]: e.description = "Tenuto da {}".format(course[FIELD_TEACHING_TEACHER_NAME].title()) e.begin = lecture[LECTURE_START] e.end = lecture[LECTURE_END] e.created = datetime.today().astimezone() if lecture[LECTURE_LOCATION]: e.location = lecture[LECTURE_LOCATION] if course[FIELD_TEACHING_URL]: e.url = course[FIELD_TEACHING_URL] return e
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
def createcalendar(): calendar = Calendar() timezone = pytz.timezone("Asia/Singapore") start_date = str(input("Start date (DD/MM/YYYY): ")) start_date = timezone.localize( datetime.datetime.strptime(start_date, "%d/%m/%Y")) current_date = None for c, day in enumerate(day_dict.keys()): schedule = day_dict[day] events = [i for i in schedule if i['name'] != 'No Lesson'] events_namelist = [i['name'] for i in events] duration = [] final = [] for i in events: if any(i['name'] == d['name'] for d in final) is False: final.append({ "name": i['name'], "duration": events_namelist.count(i['name']), "begin": i['time'][0:4], 'venue': i['venue'] }) for i in final: e = Event() e.name = i['name'] e.description = i['venue'] if c <= 4: current_date = start_date.replace( hour=int(i['begin'][:2]), minute=int( i['begin'][2:4])) + datetime.timedelta(hours=24 * c) elif c > 4: current_date = start_date.replace( hour=int(i['begin'][:2]), minute=int( i['begin'][2:4])) + datetime.timedelta(hours=24 * (c + 2)) e.begin = current_date e.end = current_date + datetime.timedelta( minutes=int(i['duration']) * 30) calendar.events.add(e) with open(f'{args.outputname}.ics', 'w') as f: f.writelines(calendar)
async def main(): s = spond.Spond(username=username, password=password) c = Calendar() c.method = 'PUBLISH' events = await s.getEvents() for event in events: e = Event() e.uid = event['id'] e.name = event['heading'] e.description = event['description'] e.begin = event['startTimestamp'] e.end = event['endTimestamp'] e.sequence = event['updated'] if 'cancelled' in event and event['cancelled']: e.status = 'Cancelled' if 'location' in event: e.location = "{}, {}".format(event['location']['feature'], event['location']['address']) c.events.add(e) with open(ics_file, 'w') as out_file: out_file.writelines(c) await s.clientsession.close()
def main(filepath): with open(filepath, 'r') as f: soup = BeautifulSoup(f.read(), features="html.parser") # sessions = soup.findAll('div', {"class": "xExpand"}) try: calendar = Calendar() with open('idv2020.csv', 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(['date', 'title', 'author', 'abstract']) for session in find_sessions(soup): e = Event() e.name = session['title'] e.begin = session['begin'].astimezone(timezone('US/Pacific')) #.strftime("%Y%m%d %H:%M:%S") # '20140101 00:00:00' e.end = session['end'].astimezone(timezone('US/Pacific')) e.description = session['abstract'] calendar.events.add(e) csvwriter.writerow(session.values()) finally: with open('idv2020.ics', 'w') as f1: f1.writelines(calendar)
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 xml_to_ics(fp): c = Calendar() tree = etree.parse(fp) root = tree.getroot() fields = None for node in root: for taak in node: fields = {f.tag: f.text for f in taak} # create ics event e = Event() e.name = "{} - {} ({})".format(fields["TAAK_GEBRUIKERCODE"], fields["TAAK_OMSCHRIJVING"], fields["TAAK_TAAKSOORT"]) e.begin = fields["TAAK_BEGINDATUM"] e.end = fields["TAAK_EINDDATUM"] if "TAAK_OPMERKING" in fields.keys(): e.description = fields["TAAK_OPMERKING"] c.events.add(e) return c
def concert_page_changed(concert_page): logger.info('Generating new iCal file with concerts from %s...', concert_page.title) c = Calendar() concerts = concert_page.sort_visible_concerts() for concert in concerts: e = Event() band_info_html = str(concert['band_info']) # Add spaces before HTML is stripped so text isn't mashed band_info = strip_tags(band_info_html.replace('><', '> <')) e.name = strip_tags(band_info) if concert['show_time']: event_start = datetime.datetime(year=concert.soonest_date.year, month=concert.soonest_date.month, day=concert.soonest_date.day, hour=concert['show_time'].hour, minute=concert['show_time'].minute, tzinfo=concert.soonest_date.tzinfo) e.begin = event_start e.end = event_start + datetime.timedelta(hours=3) else: # Start time to be determined event_start = datetime.datetime(year=concert.soonest_date.year, month=concert.soonest_date.month, day=concert.soonest_date.day, hour=0, minute=0, tzinfo=concert.soonest_date.tzinfo) e.begin = event_start e.end = event_start + datetime.timedelta(hours=24) e.description = 'Concert Time TBD. Check back soon.' c.events.add(e) with default_storage.open(f'concert_calendar_{concert_page.slug}.ics', mode='w') as cal_file: if settings.DEFAULT_FILE_STORAGE == 'home.custom_storages.MediaStorage': # S3 Storage seems to require bytes regardless of write mode for line in c: cal_file.write(line.encode('utf-8')) else: cal_file.writelines(c)
def resolve_event(evt_html): title = evt_html('.event_title a').text() if title.endswith('Test'): return None evt = Event( name=(f'MotoGP {_FLAGS[evt_html(".location span").eq(1).text()]} ' f'{title} ({os.environ["SESSIONS"]})'), location=evt_html('.location span').eq(0).text(), url=f'{evt_html(".event_title a").attr("href")}#schedule') desc = [] begin = None end = None sched_html = pq(url=evt.url, encoding='utf-8') for e in sched_html('.c-schedule__table-row').items(): sessions = e( '.c-schedule__table-cell:nth-child(3) span.hidden-xs').text() if not sessions.startswith(os.environ['SESSIONS']): continue category = e('.c-schedule__table-cell').eq(1).text().strip() ini_time = e('.c-schedule__time span').eq(0).attr('data-ini-time') if begin is None: begin = ini_time else: end = ini_time desc.append(f'{ini_time} {category} {sessions}') td = datetime.strptime(end, TIME_FMT) - datetime.strptime(begin, TIME_FMT) evt.begin = begin evt.description = '\n'.join(desc) evt.duration = timedelta(seconds=td.seconds + 7200) print(f'{evt.name}\n' f'Circuit: {evt.location}\n' f'Schedule:\n{evt.description}\n{"-" * 46}') return evt
def DefEv1(nome, categoria, description, tipo, dias, horas, osm, wikidata, wikipedia, facebook, instagram, twitter, youtube, teams, stream, c): e = Event() e.name = nome Descricao = ConcatenarDescrição(categoria, description, wikidata, wikipedia, facebook, instagram, twitter, youtube, teams, stream) e.description = Descricao e.location = osm soma = int(horas[0:2]) soma = soma + 3 strsoma = str(soma) hinicio = dias[0:4] + '-' + dias[5:7] + '-' + dias[ 8:10] + ' ' + strsoma + horas[2:5] + ':00' soma = int(horas[6:8]) soma = soma + 3 strsoma = str(soma) hfinal = dias[0:4] + '-' + dias[5:7] + '-' + dias[ 8:10] + ' ' + strsoma + horas[8:11] + ':00' e.begin = hinicio e.end = hfinal c.events.add(e)
def export_file(events: List[EventEntity], file_path: str): c = Calendar() for event in events: e = Event() e.name = event.name e.description = event.description e.begin = event.date_start e.end = event.date_end e.uid = event.uid e.extra.append(ContentLine(name="MYDURATION", value=event.duration)) e.extra.append(ContentLine(name="LOOSE", value=event.loose)) e.extra.append(ContentLine(name="PRIORITY", value=event.priority.name)) e.extra.append(ContentLine(name="DAYTIME", value=event.day_time.name)) e.extra.append(ContentLine(name="TIMEWINDOW", value=event.time_window)) e.extra.append(ContentLine(name="TIMEBEFORE", value=event.time_after)) e.extra.append(ContentLine(name="TIMEAFTER", value=event.time_before)) c.events.add(e) with open(file_path, 'w') as f: f.write(str(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.get_weeks_nb()): dates = [] 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))
def calendar_view(request, whatever): from ics import Calendar, Event user, params = _get_action_request_params(request) date_range = _make_date_range(params['date'], include_future=True, include_past=30) actions = Action.objects.for_user(user).filter(when__date__range=date_range) thecal = Calendar() thecal.creator = 'XR Mass Events' for action in actions: evt = Event() evt.uid = '{}@{}'.format(action.id, request.get_host()) evt.name = action.html_title evt.description = action.description evt.categories = action.tags.names() evt.last_modified = action.modified evt.url = request.build_absolute_uri(action.get_absolute_url()) evt.begin = action.when evt.duration = timedelta(hours=1) # evt.end = action.when + timedelta(hours=1) evt.location = action.location thecal.events.add(evt) response = HttpResponse(thecal, content_type='text/calendar') return response
def DefEv2(i, nOcorrencias, nome, Descricao, osm, horas, dias, c): a = Event() auxH = (i - 1) * 11 + i - 1 auxD = ((i - 1) * 10) + i - 1 a.name = "[" + str(i) + "/" + str(nOcorrencias) + ']' + nome a.description = Descricao a.location = osm soma = int(horas[0 + auxH:2 + auxH]) soma = soma + 3 strsoma = str(soma) hinicio = dias[0 + auxD:4 + auxD] + '-' + dias[5 + auxD:7 + auxD] + '-' + dias[ 8 + auxD:10 + auxD] + ' ' + strsoma + horas[2 + auxH:5 + auxH] + ':00' soma = int(horas[6 + auxH:8 + auxH]) soma = soma + 3 strsoma = str(soma) hfinal = dias[0 + auxD:4 + auxD] + '-' + dias[5 + auxD:7 + auxD] + '-' + dias[ 8 + auxD:10 + auxD] + ' ' + strsoma + horas[8 + auxH:11 + auxH] + ':00' a.begin = hinicio a.end = hfinal c.events.add(a)
def handle_sncf_message(self, message): payload = list(message.walk())[1].get_payload() 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 = 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 c.events.add(e) c.events with open('my.ics', 'w') 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))
def makeFile(week=5): c = Calendar() today = datetime.date.today() chetn = 0 # UserParams.getChetn() current_date = today - datetime.timedelta( days=today.isoweekday()) + datetime.timedelta(days=1) days_in_week = list(response.keys()) days_in_week.sort() current_week = 0 while (current_week <= week): for key in days_in_week: if (current_date.month == 12 and current_date.day == 30) or (current_date.month == 7 and current_date.day == 1): break for row in response[key]: dayDate = row["dayDate"].rstrip().lower() chetnost = True if ( datetime.date(current_date.year, current_date.month, current_date.day).isocalendar()[1] + chetn) % 2 else False # Если True чет, False - неч prefix = "" if (dayDate == 'чет' and not chetn) or (dayDate == 'неч' and chetn): continue elif dayDate == 'чет/неч': if chetnost: prefix = " (1) гр." else: prefix = " (2) гр." elif dayDate == 'неч/чет': if chetnost: prefix = " (2) гр." else: prefix = " (1) гр." e = Event() tt = row["dayTime"].rstrip() if len(row["dayTime"].rstrip( )) < 6 else row["dayTime"].rstrip()[:5] tt = tt_dict[tt] begin_time = str(current_date) + " {}:00".format(tt) # end_time = str(current_date) + " {}:00".format(time_dict[row["dayTime"].rstrip()]) e.name = prefix + row["disciplType"].rstrip().upper( ) + " " + row["disciplName"].rstrip() e.begin = begin_time e.duration = datetime.timedelta( minutes=190 if row["disciplType"].rstrip().upper() == 'Л.Р.' else 90) e.location = "В {} ауд. {} зд".format(row["audNum"].rstrip(), row["buildNum"].rstrip()) e.description = "В {} ауд. {} зд".format( row["audNum"].rstrip(), row["buildNum"].rstrip()) c.events.add(e) current_date = current_date + datetime.timedelta(days=1) if str(current_date.isoweekday()) not in days_in_week: current_date = current_date + datetime.timedelta(days=1) continue current_week += 1 with open('my.ics', 'w') as f: f.write(str(c))
import sys import datetime import time import json from ics import Calendar, Event filename = sys.argv[1] jfile = open(filename, "r") if jfile.mode == "r": jdata = jfile.read() jfile.close() data = json.loads(jdata) c = Calendar() for meeting in data: if meeting["Name"] != "": newEvent = Event() newEvent.name = meeting["Name"] newEvent.begin = meeting["Beginning"] newEvent.end = meeting["Ending"] newEvent.description = "Meets in room " + meeting["Room"] + "." c.events.append(newEvent) print(str(c))
from ics import Calendar, Event c = Calendar() e = Event() e.name = "K-WORLD FESTA" e.begin = '2019-08-15 18:30:00' e.end = '2019-08-15 23:59:59' e.description = 'K-WORLD FESTA Opening Concert' e.location = 'KSPO DOME' e.url = 'https://www.kworldfesta.com/kspodome' #e.categories = '' #e.status = 'Group' c.events.add(e) c.events # {<Event 'K-World Festa' begin:2019-08-15 18:00:00 end:2019-08-15 21:00:00>} with open('DC.ics', 'w') as f: f.writelines(c) # And it's done!
def generate_match_calendar(matches): """ Generate a .ics file of matches from a list of dictionaries. Arguments: matches -- A list of dicts containing all matches. (list) """ cal = Calendar() # Set Calendar Metadata cal.extra.append(ContentLine(name='X-WR-CALNAME', value='KQB Matches')) cal.extra.append( ContentLine( name='X-WR-CALDESC', value= 'Upcoming matches and events in the Killer Queen Black community.') ) cal.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT15M')) cal.extra.append(ContentLine(name='TZNAME', value='UTC')) # Add all events to calendar for match in matches: event = Event() home_team = match['home'] away_team = match['away'] if match['circuit']['name']: circuit_name = match['circuit']['name'] else: circuit_name = match['circuit']['verbose_name'] circuit_abbrev = f"{match['circuit']['tier']}{match['circuit']['region']}" # This should not happen anymore, but just to be safe. if (not home_team or not away_team): continue event.name = f"{circuit_abbrev} {away_team['name']} @ {home_team['name']}" event.begin = dp.parse(match['start_time']) event.duration = timedelta(minutes=60) # Tier and Circuit description = f'🌐 {circuit_name}' # Add Caster Details to Description if match['primary_caster']: description += f'\n\n🎙️ Casted by {match["primary_caster"]["name"]}' if match['secondary_casters']: description += f'\nCo-Casted by ' for cocaster in match['secondary_casters']: description += cocaster + ',' # Get rid of trailing comma description = description.rstrip(',') # Stream Link if match['primary_caster']['stream_link']: description += f"\n{match['primary_caster']['stream_link']}" # Away Team Stats description += f"\n\n🔷 {away_team['name']} [{away_team['wins']}W/{away_team['losses']}L]" description += '\n\n' for member in away_team['members']: description += f"{member['name']}, " description = description.rstrip(', ') # Home Team Stats description += f"\n\n🔶 {home_team['name']} [{home_team['wins']}W/{home_team['losses']}L]" description += '\n\n' for member in home_team['members']: description += f"{member['name']}, " description = description.rstrip(', ') event.description = description # Finalize Event cal.events.add(event) with open('matches.ics', 'w') as cal_file: cal_file.writelines(cal)
# 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 construct_and_write_calendar_files(cal_dict, bold: bool): now = datetime.now() date = now.strftime('%m-%d-%Y') calendar = Calendar() if bold: filename = date + ' bold calendar items' else: filename = date + ' all calendar items' # with open(f'{filename}.csv', 'w') as csvfile: # cal_writer = csv.writer(csvfile) # cal_writer.writerow(['Subject', # 'Start Date', 'Start Time', # 'End Date', 'End Time', # 'Description', 'Location']) for date, events in cal_dict.items(): # create the correct date format for all events within a day parts = date.split(',') year = parts[2][1:] month_day = parts[1].split(' ') month = month_dict[month_day[1]] day = month_day[2] date_combined = year + '/' + month + '/' + day for event in events: # subject subject = event[1] # start date and time start_date = date_combined start_time = event[0] ics_start = datetime.strptime(start_date + ' ' + start_time, '%Y/%m/%d %I:%M %p') dst_adjust_start = (ics_start + timedelta(hours=4)) if is_dst() else ( ics_start + timedelta(hours=5)) # end date and time end_date = date_combined if event[0][-2] == 'A' and event[0][:2] == '11': end_time = '12:00 PM' elif event[0][:2] == '12': end_time = '1:00 PM' else: split_time = start_time.split(':') hour = split_time[0] minute = split_time[1][:2] if event[0][-2] == 'A': indicator = 'AM' else: indicator = 'PM' end_time = str(int(hour) + 1) + ':' + minute + ' ' + indicator ics_end = datetime.strptime(end_date + ' ' + end_time, '%Y/%m/%d %I:%M %p') dst_adjust_end = (ics_end + timedelta(hours=4)) if is_dst() else ( ics_end + timedelta(hours=5)) # description if len(event) == 4: description = event[2].replace('\n', '') else: description = '' # location location = event[-1] # cal_writer.writerow([subject, # start_date, start_time, # end_date, end_time, # description, location]) event = Event() event.name = subject event.begin = dst_adjust_start event.end = dst_adjust_end event.description = description event.location = location calendar.events.add(event) # write the ics to a file with open(f'{filename}.ics', 'w') as icsfile: icsfile.writelines(calendar)
def generate_event_calendar(events): """ Generate a .ics file of events from a list of dictionaries. Arguments: events -- A list of dicts containing all matches. (list) """ cal = Calendar() # Set Calendar Metadata cal.extra.append(ContentLine(name='X-WR-CALNAME', value='KQB Events')) cal.extra.append( ContentLine( name='X-WR-CALDESC', value= 'Upcoming matches and events in the Killer Queen Black community.') ) cal.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT15M')) # Add all events to calendar for entry in events: event = Event() event.name = entry['name'] event.begin = dp.parse(entry['start_time']) if entry['duration']: date_obj = datetime.strptime(entry['duration'], '%H:%M:%S') delta = timedelta(hours=date_obj.hour, minutes=date_obj.minute, seconds=date_obj.second) event.duration = delta else: event.duration = timedelta(minutes=60) # Base Description description = str(entry['description']) # Event Links if entry['links']: description += '\n\n[Event Links]\n' for link in entry['links']: description += f"\n{link['name']}:\n{link['url']}\n" # Organizers if entry['organizers']: description += '\n\n[Organizers]\n' for organizer in entry['organizers']: description += f"{organizer['name']}" if organizer['discord_username']: description += f"discord: @{organizer['discord_username']}\n" if organizer['twitch_username']: description += f"twitch: https://twitch.tv/{organizer['twitch_username']}\n" description += '\n\n' # Finalize Description event.description = description # Finalize Event cal.events.add(event) with open('events.ics', 'w') as cal_file: cal_file.writelines(cal)
calAnw = Calendar() calEvs = Calendar() calVsi = Calendar() js = [] for event in data: #pprint(event) ev = Event() ev.name = event['description'] ev.begin = event['start'] ev.end = event['end'] ev.location = event['room'] des = event['instructor'] + ' ' + event['title'] ev.description = des calAll.events.add(ev) if ("3IT-PMA" in ev.description): color = "#cf2c08" calAnw.events.add(ev) elif("3IT-MK" in ev.description): color = "#08b4cf" calKom.events.add(ev) elif("EVSA" in ev.description): color = "#08b4cf"
temp = str(i[0]).split(" ")[0] date_object = datetime.strptime(temp, '%d/%m/%Y') timezone = pytz.timezone("Europe/Moscow") date_object = date_object.replace(tzinfo=timezone) electives_found = find_electives_in_row(electives_columns, i) if electives_found: time = i[2] begin_hour = int(time.split("-")[0].split(":")[0]) begin_minute = int(time.split("-")[0].split(":")[1]) end_hour = int(time.split("-")[1].split(":")[0]) end_minute = int(time.split("-")[1].split(":")[1]) begin = date_object.replace(hour=begin_hour, minute=begin_minute) end = date_object.replace(hour=end_hour, minute=end_minute) for elective in electives_found: e = Event() e.name = elective["name"] e.description = elective["description"] e.begin = begin e.end = end c.events.add(e) print("You have chosen the following electives:") for elective in electives: print(f"* {elective}") print(f"You got a calendar 'Electives.ics' with {len(c.events)} events.") open('Electives.ics', 'w').writelines(c)
if pd.isnull(plan.loc[index].Sala): plan.loc[index, 'Sala'] = "e-learning" plan = plan.drop(columns=['Przedmiot']) plan = plan[plan.columns[[6, 5, 0, 1, 2, 3, 4]]] export = pd.DataFrame(columns=plan.columns) for index, row in plan.iterrows(): daty = plan.loc[index].Daty[:-1].split(';') for data in daty: plan.loc[index].Daty = data export = export.append(plan.loc[index], ignore_index=True) c = Calendar() for index, _ in export.iterrows(): ev = export.loc[index] e = Event() e.name = ev.Nazwa e.begin = parser.parse(''.join((ev.Daty, ' ', ev.Poczatek, ' CEST')), dayfirst=True) e.end = parser.parse(''.join((ev.Daty, ' ', ev.Koniec, ' CEST')), dayfirst=True) e.location = ev.Sala e.description = ev.Prowadzący c.events.add(e) file = open('plan.ics', 'w') file.writelines(c) file.close()
def makeClass(calendar, classesStartDate, classesEndDate): startOfSemesterDT = "" endOfSemesterDT = "" startOfSemesterICS = "" endOfSemesterICS = "" if type(classesStartDate) is str: startOfSemesterDT = localTimeToUTC(ICSToDateTime(classesStartDate)) endofSemesterDT = localTimeToUTC(ICSToDateTime(classesEndDate)) startOfSemesterICS = classesStartDate endOfSemesterICS = classesEndDate else: startOfSemesterDT = localTimeToUTC(classesStartDate) endOfSemesterDT = localTimeToUTC(classesEndDate) startOfSemesterICS = dateTimeToICS(localTimeToUTC(classesStartDate)) endOfSemesterICS = dateTimeToICS(localTimeToUTC(classesEndDate)) name = input("What is the class name? ") daysOfClassChars = input("What are the days for the class? (MTWRFSU) ") location = input("Where is the class held? ") professor = input("Who is the professor? ") startTime = input("When does the class start? (HH:MM) ") endTime = input("When does the class end? (HH:MM) ") days = ['M', 'T', 'W', 'R', 'F', 'S', 'U'] weekdayOfStartOfSemester = startOfSemesterDT.weekday() % len(days) weekdayOfStartOfClass = 0 for i in range(weekdayOfStartOfSemester, len(days)): for dayChar in daysOfClassChars: if days[i] is dayChar: weekdayOfStartOfClass = i weekdaysOfClassInts = [] for dayOfClass in daysOfClassChars: for i in range(0, len(days)): if dayOfClass is days[i]: weekdaysOfClassInts.append(i) nextDT = nextWeekday(startOfSemesterDT, weekdayOfStartOfClass) classStart = localTimeToUTC( datetime(nextDT.year, nextDT.month, nextDT.day, hour=int(startTime[:2]), minute=int(startTime[3:]))) classEnd = localTimeToUTC( datetime(classStart.year, classStart.month, classStart.day, hour=int(endTime[:2]), minute=int(endTime[3:]))) allDTs = getAllDTs(classStart, classEnd, endOfSemesterDT, weekdaysOfClassInts) events = [] for dates in allDTs: temp = Event() temp.name = str(name) temp.description = "Professor: " + str(professor) temp.begin = dates[0] temp.end = dates[1] temp.location = str(location) events.append(temp) return events
recommended_recipes = [items[0] for items in recommended_recipes][:3] print(recommended_recipes) # ### create calendar file # In[46]: event_description = "" expired_items = pd.read_csv('expiring_items.csv') for index, row in expired_items.iterrows(): event_description = event_description + str(row['Name']) + " in " + str( row['days to expire']) + " days\n" event_description = event_description + "\n" + "Suggested Recipes: \n" for recipe in recommended_recipes: event_description = event_description + recipe + "\n" c = Calendar() e = Event() e.name = "Items expiring this week" e.description = event_description e.begin = today c.events.add(e) c.events with open('my.ics', 'w') as my_file: my_file.writelines(c) # In[ ]:
def process_game_schedule(cal: Calendar) -> None: """ This processes the game schedule, unfortunately the page formats for the practices and the games are completely different and require different parsers. """ print('\nGames') print('=====\n') # Determine if we need to use a proxy then request the target web page. if True == config['proxies']['enable']: page = requests.get(config['practice']['url'], proxies=config['proxies']) else: page = requests.get(config['practice']['url']) # Parse the document into a HTML document tree = html.fromstring(page.content) # Find the table body with schedule data. The xpath was determined by # inspecting elements in Chrome/Firefox and copying the xpath. nodes = tree.xpath(config['practice']['xpath']) row_num = 0 for node in nodes: # The schedule data we want is in every other row. Each cell within # that row contains a separate piece of schedule data. So the relative # xpath we need to use is /tr[row_num]/td[cell_num]/div row_num += 1 # Skip even numbered rows as they contain hidden table data, its data we # actually want but it is in a form harder to parse. if 0 == (row_num % 2): continue date = node.xpath('//tr[{}]/td[1]/div/text()'.format(row_num)) time = node.xpath('//tr[{}]/td[2]/div/text()'.format(row_num)) home_team = node.xpath('//tr[{}]/td[3]/div/text()'.format(row_num)) away_team = node.xpath('//tr[{}]/td[4]/div/text()'.format(row_num)) rink = node.xpath('//tr[{}]/td[5]/div/text()'.format(row_num)) # Not sure why but there seem to be way more nodes than there are rows # in the table, so we just do a quick check here. If date is empty then # we have hit the end of the schedule and can exit. if not date: break # print(date[0], time[0], home_team[0], away_team[0], rink[0]) if config['team'].lower() == home_team[0].lower().strip() or \ config['team'].lower() == away_team[0].lower().strip(): # Pretty print the team match up. pretty_title = home_team[0].title().strip() + ' vs ' + \ away_team[0].title().strip() # Reformat the date time string start_time = time[0].split('-') event_time = format_date_time(date[0], start_time[0]) print('{:24} - {} on {}'.format(pretty_title, event_time, rink[0])) event = Event() event.name = pretty_title + ' (game)' event.begin = event_time event.duration = {'hours': 1} event.description = rink[0] event.location = config['location'] cal.events.append(event)
def generate_ics_calendar(self, filename=''): logger.debug(f"Refreshed ICS for {self.username}") @MemoizeWithTimeout() def format_ics_date(event_date): return get_ade_timezone().localize( datetime.strptime(event_date, '%d/%m/%Y %H:%M')) def format_ics_location(classroom): return f'{classroom["name"]} ({", ".join(classroom["genealogy"])})' def format_geolocation(classrooms): try: # Returns the first geolocation found return next(filter( None, (c.get('geolocation') for c in classrooms)))[:2] except Exception: return None @MemoizeWithTimeout() def format_end_date(dt, offset): return dt + timedelta( minutes=(int(offset) * settings.ADE_DEFAULT_DURATION)) def format_description(resources): descriptions = [] # TODO: i18n ? for key, display in {'trainees': 'Filières', 'instructors': 'Intervenants', 'category5s': 'Matières'}.items(): if key in resources: descriptions.append( f'{display} : ' + ','.join([x['name'] for x in resources[key]])) return '\n'.join(descriptions) filename = filename or self.ics_calendar_filename calendar = Calendar() if self.events_nb > settings.ADE_MAX_EVENTS: logger.warning(f'Too much events for {self.username} : {self.events_nb}') e = Event() e.name = "Votre calendrier dépasse le nombre d'événements autorisé" e.begin = format_ics_date('01/01/2000 00:00') e.end = format_ics_date('01/01/2100 00:00') calendar.events.add(e) else: merged_events = self.events events = merged_events.get('events', []) # merged_events = {r: merged_events.get(r, {}) for r in res_list} if events: filename = filename or self.ics_calendar_filename res_list = ('trainees', 'instructors', 'classrooms', 'category5s') for event in events: # Keeps adding 5000 events under 1 sec resources = {} for r in res_list: res = [merged_events[r][e] for e in event.get(r, [])] if res: resources[r] = res classrooms = resources.get('classrooms', ()) begin_time = format_ics_date( f'{event["date"]} {event["startHour"]}') # Genereate ICS event e = Event() e.name = event['name'] e.begin = begin_time e.end = format_end_date(begin_time, event['duration']) e.geo = format_geolocation(classrooms) e.location = ';'.join(map(format_ics_location, classrooms)) # e.last_modified = event['lastUpdate'] e.description = format_description(resources) calendar.events.add(e) if self.events_nb > 0: with default_storage.open(filename, 'w') as fh: return fh.write(str(calendar))
return True if __name__ == "__main__": username = input('请输入用户名:') password = getpass.getpass('请输入密码:') c = Calendar() jwxt = Jwql(username, password) classes = jwxt.get_classes("2019-2020-2", term_start_time) for class_ in classes: print('---------------------------') print('课程名:', class_.name) print('任课教师:', class_.teacher) print('上课周数', class_.weeks) print('上课星期:', class_.weekday) print('上课节次:', class_.session) print('上课节数:', class_.number) print('上课地点:', class_.location) if check(): for time_ in class_.time: e = Event() e.name = class_.name e.begin = time_.start_time.isoformat() e.end = time_.end_time.isoformat() e.location = class_.location e.description = class_.teacher c.events.add(e) with open('my.ics', 'w', encoding='utf-8') as my_file: my_file.writelines(c)
def process_practice_schedule(cal: Calendar) -> None: """ This processes the practice schedule, unfortunately the page formats for the practices and the games are completely different and require different parsers. """ print('\nPractice') print('========\n') # Determine if we need to use a proxy then request the target web page. if True == config['proxies']['enable']: page = requests.get(config['practice']['url'], proxies=config['proxies']) else: page = requests.get(config['practice']['url']) # Parse the document into a HTML document tree = html.fromstring(page.content) # Find all the td elements with schedule data. The xpath was determined by # inspecting elements in Chrome/Firefox and copying the xpath. nodes = tree.xpath(config['practice']['xpath']) for node in nodes: element = node.xpath('@title|@data-content') # print('type: ', type(element), ', len:', len(element)) if 0 < len(element): # raw_title is the team match up i.e. 'TEAM1 vs TEAM2' # details is a list 0 = date, 1 = time, 2 = location # - date 'DDD MMM dd, YYYY' # - time 'hh:mm AM/PM - hh:mm AM/PM' # - location 'Location: <North/South> Pole' raw_title = str(element[0]) details = str(element[1]).split('<br>') # Filter on our team if config['team'].lower() in raw_title.lower(): # Pretty print the team match up. teams = raw_title.split(' vs ') pretty_title = teams[0].title() + ' vs ' + teams[1].title() # Reformat the date time string event_time = format_date_time(details[0], details[1]) rink = details[2].strip('Location: ') print('{:24} - {} on {}'.format(pretty_title, event_time, rink)) event = Event() event.name = pretty_title + ' (prac)' event.begin = event_time event.duration = {'hours': 1} event.description = rink event.location = config['location'] cal.events.append(event)
def event_generator(units): # set up a calendar c = Calendar() c.creator = "The Null Pointers" # set up a dictionary for the general week events weekly = {} for i in range(1,14): weekly[i] = [] # set up a list of formal exams final_exams = [] for unit in units: for assessment in unit.list_of_assessments: # if the assessment has a due date we want to create an event # for it if assessment.due_date != None: e = Event() e.name = unit.code + ": " + assessment.description_title + " (" + "weighting: " + assessment.weight + ")" date = arrow.get(assessment.due_date, "DD MMM YYYY") e.begin = date e.description = assessment.description_body c.events.add(e) if assessment.due_str.startswith("Week "): week = int(assessment.due_str.split()[1]) weekly[week].append(assessment) if assessment.is_final: final_exams.append(assessment) # loop through the general weekly assessments for week in sorted(weekly.keys()): if weekly[week] == []: continue e = Event() e.name = "Week " + str(week) + " Assessments" desc = "" for assessment in weekly[week]: desc += assessment.unit.code +": " + assessment.description_title + " (weighting: " + assessment.weight + ")"+ "\n" # shift by 1 to account for midsem break if week > 7: week += 1 date = start_sem.shift(weeks=week-1) e.begin = date e.description = desc c.events.add(e) if final_exams != []: e = Event() e.name = "Your final exams" desc = "" for assessment in final_exams: desc += assessment.unit.code + ": " + assessment.description_title + " (weighting: " + assessment.weight + ")" + "\n" e.description = desc e.begin = formal_exam_period c.events.add(e) with open('static_files/calendar.ics', 'w+') as my_file: my_file.writelines(c)
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: for line in lines: file.write(line)