def as_ical(self): event = Event() event.name = ' and '.join(collection.type for collection in self._collections) event.begin = self.date event.end = self.date.replace(hour=8, minute=10) return event
def post(self): data = request.get_json() if data is None: abort(400, 'Trip Data not received') itinerary = data.get('itinerary') # start_date = data.get('startdate') # start = datetime.strptime(start_date,'%y-%m-%d %H:%M:%S') # # account for gmt, sydney+11 # start = start - timedelta(hours=-11) # # assume starting day at 9am # start = start + timedelta(hours=9) c = Calendar() for event in itinerary: e = Event() e.name = event['name'] e.begin = datetime.strptime( event['start'], '%Y-%m-%dT%H:%M:%S.000Z' ) #+timedelta(hours=-11) #account for tz e.duration = timedelta(minutes=event['duration']) c.events.add(e) # with open('my.ics', 'w') as f: # f.write(str(c)) return {"content": str(c)}
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 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 team_ics(team): matches = Matches().get_matches(lambda m: m.doesFeature(team)) c = Calendar() for m in matches: if not m._date: continue e = Event(uid=fixture_uid(m), location=m.venue) e.name = "%s vs %s" % (m.home, m.away) if not m._time: m._time = time(0,0,0) begin = datetime(m._date.year, m._date.month, m._date.day, m._time.hour, m._time.minute, m._time.second) begin = arrow.get(begin, 'Europe/London') e.begin = begin e.duration = timedelta(minutes=90) c.events.append(e) return Response(c, mimetype='text/calendar')
def add_course(kurs): r = requests.get(f"https://www.fu-berlin.de/vv/de/search?query={kurs}") soup = BeautifulSoup(r.text) dates = [(text.text.strip().split(" ")[1], text.text.strip().split(" ")[2], text.text.strip().split(" ")[4]) for text in soup.find_all(class_="course_date_time")] for date in dates: e = Event() e.name = soup.find_all("h1")[1].text year = date[0].split(".")[2] month = date[0].split(".")[1] day = date[0].split(".")[0] starthours = date[1].split(":")[0] startminutes = date[1].split(":")[1] endhours = date[2].split(":")[0] endminutes = date[2].split(":")[1] seconds = "00" begin = arrow.get( year + "-" + month + "-" + day + " " + starthours + ":" + startminutes + ":" + seconds, 'YYYY-MM-DD HH:mm:ss') begin = begin.replace(tzinfo='Europe/Paris') begin = begin.to("utc") e.begin = begin.format('YYYY-MM-DD HH:mm:ss') end = arrow.get( year + "-" + month + "-" + day + " " + endhours + ":" + endminutes + ":" + seconds, 'YYYY-MM-DD HH:mm:ss') end = end.replace(tzinfo='Europe/Paris') end = end.to("utc") e.end = end.format('YYYY-MM-DD HH:mm:ss') c.events.add(e)
def generate_ical_events(self): print('Generating iCal calendar events. Please wait...') # Regex for removing HTML tags from seminar description pattern = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});') # Loop through all events in database for seminar in Seminar.objects.all(): calendar = Calendar() event = Event(name=seminar.title, begin=seminar.start_time, end=seminar.end_time, description=pattern.sub('', seminar.description), url=seminar.registration_url) if seminar.location: event.location = seminar.location.location calendar.events.add(event) # Create icalendar instance for that event seminar.icalendar = str(calendar) seminar.save() print('iCal calendar events generated!')
def unibo_calendar(): print("Options:") print("Year: " + YEAR) print("Course: " + COURSE) # Get data print("Getting json data...") url = 'https://corsi.unibo.it/laurea/' + \ str(COURSE) + "/orario-lezioni/@@orario_reale_json?anno=" + str(YEAR) events = requests.get(url).json() print(str(len(events)) + " events found!") # Build calendar calendar = Calendar() for event in events: # Build event e = Event(location=event.get("aule")[0].get("des_ubicazione"), alarms=None) e.name = event.get("title").title() + " - " + \ event.get("aule")[0].get("des_risorsa") e.begin = arrow.get(event.get("start")).replace(tzinfo="Europe/Rome") e.end = arrow.get(event.get("end")).replace(tzinfo="Europe/Rome") # Add event to calendar calendar.events.add(e) # Print file print("Writing .ics...") with open('UniboCalendar.ics', 'w') as file: file.writelines(calendar) print("Done!")
def create_ics(birthday=None, add_alarms=False, schedule_file='./vaccines.csv', ical_file='./vaccines.ics'): if birthday is None: birthday = date.today() else: birthday = parser.parse(birthday) c = Calendar() for v in load_csv(schedule_file): v = v._asdict() target_months = [k for k, v_ in v.items() if k.startswith('M') and v_] total = v[target_months[-1]] for month in target_months: name = v['name'] + f' {v[month]}/{total}' begin = birthday + relativedelta(months=int(month[1:])) if add_alarms: alarms = [DisplayAlarm(trigger=timedelta(hours=1))] else: alarms = None e = Event(name=name, begin=begin, description=v['abbv'], alarms=alarms) e.make_all_day() c.events.add(e) with open(ical_file, 'w') as f: f.writelines(c)
def make_calendar(): cal = Calendar() cal.events.append(Event("second", datetime(2000, 2, 1, 12, 0))) cal.events.append(Event("fourth", datetime(2000, 4, 1, 12, 0))) cal.events.append(Event("third", datetime(2000, 3, 1, 12, 0))) cal.events.append(Event("first", datetime(2000, 1, 1, 12, 0))) return cal
def download(): if request.method =="GET": c = Calendar() events=query_db("SELECT * FROM events WHERE user_id=?",[session["user_id"]]) for x in events: utc=pytz.utc eastern=pytz.timezone('US/Eastern') if x[8]: local_datetime = datetime(int(x[3][0:4]), int(x[3][5:7]), int(x[3][8:]),int(x[8][0:2]),int(x[8][3:5])) else: local_datetime = datetime(int(x[3][0:4]), int(x[3][5:7]), int(x[3][8:])) date_eastern=eastern.localize(local_datetime,is_dst=None) date_utc=date_eastern.astimezone(utc) e = Event() e.name = x[1] e.begin = date_utc.strftime('%Y-%m-%d %H:%M:%S') #x[3] + " " + x[8] + ":00" c.events.add(e) with open('calendars/'+str(session["user_id"])+'.ics', 'w') as f: f.write(str(c)) ##download file path = "calendars/"+str(session["user_id"])+".ics" return send_file(path, as_attachment=True, cache_timeout=0) if request.method=="POST": return redirect("/")
def make_event(self): ics = Calendar() event = Event() # check for existing work shift # if there is one, delete it and replace with the new one # because it's possible the shift has changed split = self.date.split('-') # print("looking in calendar for date: " + self.date) try: todayshift = calendar.date_search( datetime(int(split[0]), int(split[1]), int(split[2])), datetime(int(split[0]), int(split[1]), int(split[2]) + 1)) except ValueError: print("it's next month for next day.") todayshift = calendar.date_search( datetime(int(split[0]), int(split[1]), int(split[2])), datetime(int(split[0]), int(split[1]) + 1, 1)) for e in todayshift: e.load() if "<SUMMARY{}work" in str(e.instance.vevent): # print("deleting existing shift") e.delete() event.name = "work - " + self.position event.begin = self.date + " " + self.start_time event.end = self.date + " " + self.end_time ics.events.add(event) # we need to get rid of the Z in the times because it implies we're using UTC # we are just using 'local' time, no time zone and ics module only supports UTC calendar.add_event(str(ics).replace("Z", ""))
def create_ics(confs, stream): cal = Calendar() """ # For standard compliance cal.add('prodid', '-//NLP CFP DB calendar//xx.url//') cal.add('version', '2.0') """ for name, data in confs.items(): begin = correct_date(data.get('begin', ''), far_future) end = correct_date(data.get('end', ''), far_future) location = data['location'] url = data['url'] for field_name in ('submission', 'notification', 'camera-ready'): add_event(cal, name, location, url, field_name.upper(), field_name, data, far_future) if begin is not None: if end < begin: end = begin # Conference e = Event(name=name, begin=datetime.combine(begin, datetime.min.time()), location=location, url=url) e.make_all_day() e.duration = end - begin + timedelta(days=1) cal.events.add(e) stream.writelines(cal)
def test_issue_188_timezone_dropped(): assert "DTSTART;TZID={tzid}:20200121T070000".format(tzid=Timezone.from_tzid("Europe/Berlin").tzid) in Calendar(fixture1).serialize() assert "DTSTART;TZID={tzid}:20200121T070000".format(tzid="W. Europe Standard Time") in Calendar(fixture2).serialize() assert "DTSTART;TZID={tzid}:20200121T070000".format(tzid="Europe/Berlin") in Calendar(fixture3).serialize() pacific = Timezone.from_tzid("US/Pacific") assert pacific.tzid.endswith("America/Los_Angeles") event1 = Event(begin=datetime(2014, 1, 1, 0, 0, 0, tzinfo=gettz("US/Pacific"))) event1.dtstamp = event1.dtstamp.replace(microsecond=0) ser1 = Calendar(events=[event1]).serialize() assert "DTSTART:20140101T000000Z" not in ser1 assert "DTSTART;TZID=%s:20140101T000000" % pacific.tzid in ser1 event2 = event1.clone() event2.begin = datetime(2014, 1, 1, 0, 0, 0, tzinfo=pacific) ser2 = Calendar(events=[event1]).serialize() assert "DTSTART:20140101T000000Z" not in ser2 assert "DTSTART;TZID=%s:20140101T000000" % pacific.tzid in ser2 assert event1 == event2 assert event1.begin == event2.begin assert event1.begin.tzinfo != event2.begin.tzinfo assert ser1 == ser2 deser1 = Calendar(ser1).events[0] deser2 = Calendar(ser2).events[0] assert deser1 == deser2 assert deser1 == event2
def save_ics_file(self, ics_file: str, n_events: int = 50) -> None: """ Saves n_events random events in the ics file with path ics_file :param ics_file (str): path of the ics file :param n_events (int): number of events to generate """ c = Calendar() for i in range(0, n_events): sys.stdout.write("\rCreating event %i of %i" % (i, n_events)) sys.stdout.flush() e = Event() e.name = self.get_rnd_title() (start, end, duration, created) = self.get_rnd_event_time() e.begin = start e.end = end e.duration = duration e.created = created e.description = self.get_rnd_description() e.url = self.get_rnd_url() e.location = self.get_rnd_address() c.events.add(e) with open(ics_file, 'w') as f: f.writelines(c) sys.stdout.write("\rDone") sys.stdout.flush()
def _generate_ics(self): data = self.data if data != None: c = Calendar() days = list(data.keys()) days.sort() for xday in days: day_data = data[xday] title = day_data[0].text_content() week, day = title.split(", ") week = w2n.word_to_num(week.lstrip("Week ")) day = w2n.word_to_num(day.lstrip("Day ")) offset = (week - 1) * 7 + (day) event_day = self.start_date + timedelta(days=offset) event_day = event_day.replace(hour=0, minute=0, second=0, microsecond=0) description = "".join( [str(html.tostring(el)) for el in day_data]) description = tomd.convert(description) e = Event(name="Magoosh {}".format(title), begin=event_day, end=event_day, description=description) e.make_all_day() c.events.add(e) with open(self.out_file, 'w') as f: f.writelines(c) print("File written to {}".format(self.out_file))
def generate_ics(): recommended_recipes, ingredients = get_expiring_items_and_recipes() 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 today = pd.to_datetime("today") e.begin = today + timedelta(days=6) c.events.add(e) c.events with open('expiry_reminder.ics', 'w') as my_file: my_file.writelines(c) return ingredients
def _add_event(c, title, year, month, day, start_time): e = Event() e.name = title e.begin = _build_arrow( f'{year}/{month.zfill(2)}/{day.zfill(2)} {start_time}') e.end = _build_arrow(f'{year}/{month.zfill(2)}/{day.zfill(2)} 20:00:00') c.events.add(e)
def generate_ics(): c = Calendar() e = Event() e.name = "Fireapp shift details: " e.begin = '2021-01-01 00:00:00' e.end = '2021-05-01 00:00:00' c.events.add(e) return c
def add_event_from_dtime(self, day_str, message="在宅"): event = Event() ini_dtime = self.day_parser(day_str) fin_dtime = add_n_day(ini_dtime, 1) event.name = message event.begin = self.from_datetime_to_etime_str(ini_dtime) event.end = self.from_datetime_to_etime_str(fin_dtime) self._internal_cal.events.add(event)
def printerToCalendar(planning, csv_file): for creneau in planning["creneau"]: c = Calendar() e = Event() e.name = 'piscine ' + planning['nom'] heureCreneau = list(creneau[0]) for elem in heureCreneau: if elem == ':': heureCreneau = heureCreneau[:heureCreneau.index(elem)] pass heureCreneau = ''.join(str(elem) for elem in heureCreneau) heureCreneauend = list(creneau[1]) for elem in heureCreneauend: if elem == ':': heureCreneauend = heureCreneauend[:heureCreneauend.index(elem)] pass heureCreneauend = ''.join(str(elem) for elem in heureCreneauend) minute = ''.join(str(elem) for elem in creneau[0][-2:]) minuteEnd = ''.join(str(elem) for elem in creneau[1][-2:]) #print(f"heure : {heureCreneau} et la minute : {minute}, creneau : {creneau[1]}") date = creneau[2].split(' ') # print(f" la date : {date}") datetime_object = datetime.datetime.strptime(date[2], "%B") date[2] = datetime_object.month e.begin = datetime.datetime(int(date[3]), int(date[2]), int(date[1]), int(heureCreneau), int(minute), 0, tzinfo=paris) # e.begin = creneauStr[0] # e.end = creneauStr[1] #print(date,heureCreneauend+':'+minute) e.end = datetime.datetime(int(date[3]), int(date[2]), int(date[1]), int(heureCreneauend), int(minuteEnd), 0, tzinfo=paris) # e.begin = creneauStr[0] # e.end = creneauStr[1] c.events.add(e) c.events os.chdir(r'../') if not os.path.exists('tmp'): os.mkdir('tmp') os.chdir('tmp') #planning['nom'] = nom with open(planning["nom"] + '.ics', 'a') as my_file: my_file.writelines(c) os.chdir('../fichiersAtraiter') planning['nom'] = None planning['creneau'] = [] csv_file.seek(0)
def get_cal(): c = Calendar() e = Event() e.name = "My cool event" e.begin = '2019-11-11 00:00:00' c.events.add(e) with open('my.ics', 'w') as my_file: my_file.writelines(c) return send_file("my.ics", mimetype="text/calendar", as_attachment=True)
def createEvent(subject, start, end): """Return Event object""" event = Event() event.name = str(subject) event.begin = start + datetime.timedelta(hours=-2) event.end = end + datetime.timedelta(hours=-2) return event
def generate(self): c = Calendar() c.scale = 'GREGORIAN' c.method = 'PUBLISH' c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]' c.extra.append( ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)')) c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H')) c.extra.append( ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/')) cur_date = datetime.now() for facebook_user in self.facebook_users: # Don't add extra 's' if name already ends with 's' formatted_username = f"{facebook_user.name}'s" if facebook_user.name[ -1] != 's' else f"{facebook_user.name}'" formatted_username = f'{formatted_username} Birthday' # Set date components day = facebook_user.birthday_day month = facebook_user.birthday_month year = facebook_user.birthday_year # Feb 29 special case: # If event year is not a leap year, use Feb 28 as birthday date instead if facebook_user.birthday_month == 2 and facebook_user.birthday_day == 29 and not calendar.isleap( year): day = 28 # The birth year may not be visible due to privacy settings # In this case, calculate the year as this year or next year based on if its past current month or not if year is None: year = cur_date.year if facebook_user.birthday_month >= cur_date.month else ( cur_date + relativedelta(years=1)).year # Format date components as needed month = f'{month:02}' day = f'{day:02}' # Event meta data e = Event() e.uid = facebook_user.id e.name = formatted_username e.created = cur_date e.description = f'{facebook_user}\n{generate_facebook_profile_url_permalink(facebook_user)}' e.begin = f'{year}-{month}-{day} 00:00:00' e.make_all_day() e.duration = timedelta(days=1) e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY')) c.events.add(e) self.birthday_calendar = c
def ics_event(name, start_date, duration=None, alarm_start=0.5): a = add_alarm(alarm_start) e = Event(alarms=[a]) e.name = name u = start_date e.begin = u if duration: d = datetime.timedelta(days=duration) e.duration = d return e
def add_event(calendar, topic, date, role): e = Event() if isinstance(topic, float): topic = 'Chat tracker' role = '' elif not 'p' in topic: topic = 'Chap ' + topic e.name = '%s %s' % (topic, role) e.begin = parse(date).replace(hour=15) calendar.events.add(e)
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 createCal(self, name): c = Calendar() e = Event() e.name = name e.begin = '2020-01-30 22:30:00' e.end = '2020-02-21 23:59:00' c.events.add(e) c.events with open('DD_Calendar.ics', 'w') as my_file: my_file.writelines(c)
def run(output_file): calendar = Calendar() datenames, missiondatas, descriptions = parse_website() for datename, data, desc in zip(datenames, missiondatas, descriptions): mission = get_mission(datename) location = get_location(data) begin, is_all_day = get_full_launchtime(datename, data) if begin: event = Event() event.begin = begin event.description = desc.text event.name = mission if is_all_day: event.make_all_day() event.location = location event.uid = mission.replace(" ", "") calendar.events.add(event) with open(output_file, "w") as outfile: outfile.writelines(calendar) print(calendar.events) print(len(calendar.events))
def checkOutput(year, month): if int(month) < 10: month = '0' + month page = requests.get( "http://www.weeia.p.lodz.pl/pliki_strony_kontroler/kalendarz.php?rok=" + year + "&miesiac=" + month) soup = BeautifulSoup(page.content, 'html.parser') events = soup.find_all('a', class_='active') print(events[0]['href']) desc = soup.find_all(class_='InnerBox') print(desc[0].getText()) c = Calendar() for i in range(len(events)): e = Event() e.name = desc[i].getText() if int(events[i].getText()) < 10: e.begin = year + '-' + month + '-0' + events[i].getText( ) + ' 00:00:00' e.make_all_day() else: e.begin = year + '-' + month + '-' + events[i].getText( ) + ' 00:00:00' e.make_all_day() c.events.add(e) filename = year + month + ".ics" with open(filename, 'w') as my_file: my_file.writelines(c) return send_file(filename, as_attachment=True)
def convert_to_ics(event): ev = Event() # name if event['significant'] == 'Nazionale': ev.name = "Sciopero {} Nazionale".format(event['sector']) else: ev.name = "Sciopero {} {} ({})".format(event['sector'], event['region'], event['province']) # date and time ev.begin = convert_format(event['start_date'], event['start_time']) ev.end = convert_format(event['end_date'], event['end_time']) if event['start_time'] == None: ev.make_all_day() # description ev.description = DESCRIPTION.format( get_default(event, 'modality'), get_default(event, 'labor_unions'), get_default(event, 'categories'), get_default(event, 'proclamation_date'), get_default(event, 'date_of_receipt')) return ev
def add_event(cal, name, location, url, prefix, field_name, data, far_future_date): due_date = correct_date(data.get(field_name, ''), far_future_date) if due_date < far_future_date: e = Event(name='{0}: {1}'.format(prefix, name), begin=datetime.combine(due_date, datetime.min.time()), end=datetime.combine(due_date, datetime.min.time()), location=location, url=url) e.make_all_day() cal.events.add(e)
def build_calender(time_table, alarm=15): routine = { 1: ['00:00:00', '00:45:00'], 2: ['00:50:00', '01:35:00'], 3: ['02:00:00', '02:45:00'], 4: ['02:50:00', '03:35:00'], 5: ['05:30:00', '06:15:00'], 6: ['06:20:00', '07:05:00'], 7: ['07:30:00', '08:15:00'], 8: ['08:20:00', '09:05:00'], 9: ['10:30:00', '11:15:00'], 10: ['11:20:00', '12:05:00'], } days = {'一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '日': 7} calendar = Calendar() time_detail_re = re.compile(u'星期([\u4e00-\u9fa5])(\d+)-(\d+)') duration_re = re.compile(r'(\d+)-(\d+)') term_start = datetime.strptime(time_table['开始时间'], '%Y-%m-%d').date() term_end = datetime.strptime(time_table['结束时间'], '%Y-%m-%d').date() for lesson in time_table['课表信息']: lesson_duration = lesson['学时分布'] start_week, end_week = duration_re.match(lesson_duration).groups() for time_detail in lesson['节次信息']: weekday, class_start, class_end = time_detail_re.match( time_detail['节次']).groups() for week in range(int(start_week), int(end_week) + 1): if time_detail['时间类型'] == '单周': if week % 2 != 1: continue if time_detail['时间类型'] == '双周': if week % 2 != 0: continue event = Event() event.name, event.organizer, event.location \ = lesson['课程名称'], lesson['教师姓名'], time_detail['教室'] a = AudioAlarm(trigger=timedelta(minutes=alarm)) event.alarms.append(a) base_day = term_start + timedelta(weeks=week - 1, days=days[weekday] - 1) class_start_time = datetime.strptime( routine[int(class_start)][0], '%H:%M:%S').time() class_end_time = datetime.strptime(routine[int(class_end)][1], '%H:%M:%S').time() event.begin = datetime.combine(base_day, class_start_time) event.end = datetime.combine(base_day, class_end_time) calendar.events.add(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 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 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 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 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 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))
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)
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)
# 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)
if debug: bar.update(prog) date = str(year) + str(day).zfill(3) url = 'https://hull.ombiel.co.uk/campusm/sso/calendar/course_timetable/' + date r = requests.get(url, cookies=cookie) r = r.json() day = day + 7 prog = prog + 7 if day > 364: day = 4 year += 1 locode = '' i = 1 for event in r['events']: if event['id'] not in ids: e = Event() i = i + 1 ids.append(event['id']) #this code is really bad, like I don't even, Should probably refactor this in to something better, It basically finds events with the same time and merges them locode = event['locCode'] if locode[-1:] == "." and locode[-2:-1].isalpha(): locode = locode[:-2] if locode[:-1].isalpha(): locode = locode[:-1] x = 1 length = len(r['events']) if i + 1 < length: for otherevent in r['events']: if (event['locCode'][:-2] == otherevent['locCode'][:-2]
# json_key = json.load(open('lacnic-ics-agenda2-251a62df85c7.json')) json_key = json.load(open('client_secret_1.json')) scope = ['https://spreadsheets.google.com/feeds'] credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope) gclient = gspread.authorize(credentials) gspread = gclient.open(agenda_gsheet_name) gwsheet = gspread.get_worksheet(1) # 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:
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)