def get_difference_in_calendars(old, new): """Get the dates in which an old and new Calendar differ. An Event differs if it is not included in the other calendar Arguments: old {str} -- The old calendar new {str} -- The new calendar Returns: list(str) -- A list of unique dates in DD.MM.YYYY format """ changed_dates = [] old_cal = Calendar(old) new_cal = Calendar(new) old_events = old_cal.events new_events = new_cal.events for event in old_events: if event not in new_events: changed_dates.append(event.begin.format("DD.MM.YYYY")) for event in new_events: if event not in old_events: changed_dates.append(event.begin.format("DD.MM.YYYY")) changed_dates = list(set(changed_dates)) changed_dates.sort(key=lambda date: datetime.strptime(date, '%d.%m.%Y')) print(changed_dates) return changed_dates
def main(): """ :return: None :rtype: None """ ics_url, file, wiki, debug = get_args() event_strings = [] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append("\n" + LINE_SEPARATOR + str(event)) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + "\n" + TABLE_HEADER + "\n" + "".join( event_strings) + "\n" + "".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, "Terminbot was here") page.purge()
def test_issue_181_timezone_ignored(): cal1 = Calendar(fixture1) cal2 = Calendar(fixture2) cal3 = Calendar(fixture3) begin1 = cal1.events[0].begin begin2 = cal2.events[0].begin begin3 = cal3.events[0].begin tzinfo1 = begin1.tzinfo tzinfo2 = begin2.tzinfo tzinfo3 = begin3.tzinfo assert isinstance(tzinfo1, Timezone) assert tzinfo1 == Timezone.from_tzid("Europe/Berlin") assert tzinfo1.tzid.endswith("Europe/Berlin") assert tzinfo1.tzname(begin1) == "CET" assert tzinfo1.utcoffset(begin1) == timedelta(hours=1) assert isinstance(tzinfo2, Timezone) assert tzinfo2 == Timezone.from_container(lines_to_container(fixture2_tz)) assert tzinfo2.tzid == "W. Europe Standard Time" assert tzinfo2.tzname(begin2) == "MEZ" assert tzinfo2.utcoffset(begin2) == timedelta(hours=1) assert isinstance(tzinfo3, Timezone) assert tzinfo3 == Timezone.from_container(lines_to_container(fixture3_tz)) assert tzinfo3.tzid == "Europe/Berlin" assert tzinfo3.tzname(begin3) == "MEZ" assert tzinfo3.utcoffset(begin3) == timedelta(hours=8)
def populate_birthdays_calendar(birthdays): """ Populate a birthdays calendar using birthday objects """ 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 birthday in birthdays: e = Event() e.uid = birthday.uid e.name = f"{birthday.name}'s 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 birthday.month >= cur_date.month else ( cur_date + relativedelta(years=1)).year month = '{:02d}'.format(birthday.month) day = '{:02d}'.format(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) return c
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 load_cal(entry: dict) -> Calendar: """Load the calendar from the cache or from remote according to the entry. If the calendar is supposed to be in cached but could not be found in cache, an error is thrown :param entry: representation of the entry to cache. This is the Python representation of the corresponding entry in the config file :type entry: dict :return: the calendar corresponding to the entry :rtype: Calendar :raises FileNotfoundError: if the entry was supposed to be cached but has not been cached before """ if "cache" in entry and entry["cache"]: print("Getting", entry["name"], "from cache") try: return get_from_cache(entry) except FileNotFoundError: return Calendar() else: print("Getting", entry["name"], "from remote") r = requests.get(entry["url"], allow_redirects=True) if "encoding" in entry: cal = Calendar(imports=r.content.decode( encoding=entry["encoding"])) else: cal = Calendar(imports=r.content.decode()) cal = horodate(cal, 'Downloaded at') return cal
def generate_calendar_except_break(student: Student) -> Calendar: events = IcsCalendarCase.generate_calendar(student, end_date=datetime.date(2020, 4, 17)).events events.update(IcsCalendarCase.generate_calendar(student, start_date=datetime.date(2020, 4, 27)).events) cal = Calendar() cal.events = events return cal
def create_calendar(token, enrollment_id, options): file_list = [] if options['academicCal'] or options['careerCal']: academic_calendar = Calendar() career_calendar = Calendar() for sess in get_sessions(token, enrollment_id)['calendarSessions']: e = Event() if (sess['context']['id'] == 1) and options['academicCal']: start_time = datetime.strptime(sess['session']['startTime'], '%Y-%m-%dT%H:%M:%SZ') end_time = datetime.strptime(sess['session']['endTime'], '%Y-%m-%dT%H:%M:%SZ') e.name = str(sess['session']['chapter']) + ': ' + sess['session']['name'] e.transparent = True if options['academicIsTrans'] else False if options['officeHours']: e.begin = start_time - timedelta(minutes=45) e.end = end_time + timedelta(minutes=30) else: e.begin = start_time e.end = end_time academic_calendar.events.add(e) elif (sess['context']['id'] == 2) and options['careerCal']: e.name = sess['session']['name'] e.begin = sess['session']['startTime'] e.end = sess['session']['endTime'] e.transparent = True if options['careerIsTrans'] else False career_calendar.events.add(e) if len(academic_calendar.events) > 0: academic_file_name = str(enrollment_id) + '-academic-calendar' academic_file_name = academic_file_name + '-oh.ics' if options['officeHours'] else academic_file_name + '.ics' file_list.append(academic_file_name) with open('files/' + academic_file_name, 'w') as f: f.writelines(academic_calendar) if len(career_calendar.events) > 0: career_file_name = str(enrollment_id) + '-career-calendar.ics' file_list.append(career_file_name) with open('files/' + career_file_name, 'w') as f: f.writelines(career_calendar) if options['assignmentCal']: assignment_calendar = Calendar() for assignment in get_assignments(token, enrollment_id)['calendarAssignments']: e = Event() if assignment['context']['id'] == 1: e.name = assignment['title'] e.begin = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1) e.end = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1) e.make_all_day() e.transparent = True if options['assignmentsIsTrans'] else False assignment_calendar.events.add(e) assignment_file_name = str(enrollment_id) + '-assignment-calendar.ics' file_list.append(assignment_file_name) with open('files/' + assignment_file_name, 'w') as f: f.writelines(assignment_calendar) return file_list
def populate_birthdays_calendar(birthdays): """ Populate a birthdays calendar using birthday objects """ 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() backburner = [] rearrange = False logger.info("Saving birthdays to local cache...") with open('birthdays.pkl', 'wb') as pkl_file: pickle.dump(birthdays, pkl_file) logger.info("Saved to cache (src/birthdays.pkl)") for birthday_i in range(0, len(birthdays)): birthday = birthdays[birthday_i] if (birthday.month == 2 and birthday.day == 29): rearrange = True backburner.append(birthday) del birthdays[birthday_i] birthday_i -= 1 continue if rearrange: if not (birthday.month == 2 and birthday.day == 28): birthdays.insert(birthday_i, backburner) rearrange = False birthday_i -= 1 continue e = Event() e.uid = birthday.uid e.name = f"{birthday.name}'s 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 birthday.month >= cur_date.month else ( cur_date + relativedelta(years=1)).year month = '{:02d}'.format(birthday.month) day = '{:02d}'.format(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) return c
def generate_ics(event_sources, future_only=True): calendar = Calendar() all_events = list(itertools.chain(*event_sources)) if future_only: all_events = [ event for event in all_events if event.begin.date() >= datetime.date.today() ] calendar = Calendar() for event in all_events: calendar.events.add(event) return calendar
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 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 create_ics(sender, instance, **kwargs): c = Calendar() alarm = [DisplayAlarm(trigger=timedelta(minutes=30))] e = Event() e.name = instance.title e.begin = instance.date e.end = instance.dateend e.alarms = alarm if instance.duration != None: e.duration = instance.duration if (instance.cost == 0 or instance.cost == None): cost = 'Бесплатно' e.description = str(instance.intro) + ' Стоимость: ' + str(cost) else: e.description = str(instance.intro) + ' Стоимость: ' + str(instance.cost)+ 'р.' e.location = instance.location if instance.timepad != None: e.url = instance.timepad c.events.add(e) instance.ics.delete(save=False) instance.ics.save(instance.title +'.ics', ContentFile(str(c)), save=True) #Формирование глобального файла со всеми мероприятиями global_ics = EventIndex.objects.all()[0] events = global_ics.get_children() c = Calendar() for event in events: if (event.specific.date < timezone.now()): pass else: e = Event() e.name = event.title e.begin = event.specific.date e.end = event.specific.dateend e.alarms = alarm if event.specific.duration != None: e.duration = event.specific.duration if (event.specific.cost == 0 or event.specific.cost == None): cost = 'Бесплатно' e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(cost) else: e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(event.specific.cost)+ 'р.' e.location = event.specific.location if event.specific.timepad != None: e.url = event.specific.timepad c.events.add(e) global_ics.calenadar_file.delete(save=False) global_ics.calenadar_file.save('global.ics', ContentFile(str(c)), save=True)
def addCalendar(request, eventID): curEvent = Event.objects.get(uuid= eventID) minDate = curEvent.startDate maxDate = curEvent.endDate requestData = request.POST.copy() uploadedFile = request.FILES['contents'] parsedCalendar = uploadedFile.read() cal = ICSCalendar(parsedCalendar) calendarEvents = cal.events calendarEvents[:] = [x for x in calendarEvents if not (x.begin < minDate or x.end > maxDate)] cal.events = calendarEvents newCalendar = Calendar(username= requestData.pop("name")[0], contents= str(cal), event= curEvent) newCalendar.save() return redirect(curEvent)
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)