Exemple #1
0
    def _generate_calendar(self, checkins, year=None):
        """
        Supplied with a list of checkin data from the API, generates an
        ics Calendar object and returns it.
        """
        user_url = self._get_user_url()

        c = Calendar()

        #for checkin in list(checkins)["checkins"]["items"]:
        for checkin in checkins:
            try:
                venue_name = checkin["venue"]["name"]
                tz_offset = self._get_checkin_timezone(checkin)

                e = Event()

                e.name = "@ {}".format(venue_name)
                e.location = venue_name
                e.url = "{}/checkin/{}".format(user_url, checkin["id"])
                e.uid = "{}@foursquare.com".format(checkin["id"])
                e.begin = checkin["createdAt"]

                e.end = e.begin

                # Use the 'shout', if any, and the timezone offset in the
                # description.
                description = []
                description.append("{}\n".format(e.url))
                if "shout" in checkin and len(checkin["shout"]) > 0:
                    description = [checkin["shout"]]
                description.append("Timezone offset: {}".format(tz_offset))
                e.description = "\n".join(description)

                # Use the venue_name and the address, if any, for the location.
                location = venue_name
                if "location" in checkin["venue"]:
                    loc = checkin["venue"]["location"]
                    if "formattedAddress" in loc and len(
                            loc["formattedAddress"]) > 0:
                        address = ", ".join(loc["formattedAddress"])
                        location = "{}, {}".format(location, address)
                e.location = location

                if (year is not None):
                    if (e.begin.year == year):
                        c.events.add(e)
                else:
                    c.events.add(e)
            except:
                print("Error processing {}".format(venue_name))
                continue
        return c
Exemple #2
0
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)
Exemple #3
0
    def _generate_calendar(self, checkins):
        """Supplied with a list of checkin data from the API, generates
        an ics Calendar object and returns it.

        Keyword arguments:
        checkins -- A list of dicts, each one data about a single checkin.
        """
        user = self._get_user()

        c = Calendar()

        for checkin in checkins:
            if "venue" not in checkin:
                # I had some checkins with no data other than
                # id, createdAt and source.
                continue

            venue_name = checkin["venue"]["name"]
            tz_offset = self._get_checkin_timezone(checkin)

            e = Event()

            e.name = "@ {}".format(venue_name)
            e.location = venue_name
            e.url = "{}/checkin/{}".format(user["canonicalUrl"], checkin["id"])
            e.uid = "{}@foursquare.com".format(checkin["id"])
            e.begin = checkin["createdAt"]

            # Use the 'shout', if any, and the timezone offset in the
            # description.
            description = []
            if "shout" in checkin and len(checkin["shout"]) > 0:
                description = [checkin["shout"]]
            description.append("Timezone offset: {}".format(tz_offset))
            e.description = "\n".join(description)

            # Use the venue_name and the address, if any, for the location.
            location = venue_name
            if "location" in checkin["venue"]:
                loc = checkin["venue"]["location"]
                if "formattedAddress" in loc and len(loc["formattedAddress"]) > 0:
                    address = ", ".join(loc["formattedAddress"])
                    location = "{}, {}".format(location, address)
            e.location = location

            c.events.add(e)

        return c
    def add_course(self, course_name, start):
        local = self.info[start].lstrip(
            str(re.search(r'<td>|<td rowspan=\"\d\">',
                          self.info[start]))).rstrip('</td>')
        weekday = re.findall(r"星期.", self.info[start + 1])[0].lstrip('星期')
        weekday = self.map.index(weekday)
        time = re.findall(r"\d+", self.info[start + 1])
        week = self.info[start + 2].lstrip('</td>第').rstrip('周</td>')
        remark = self.info[start + 3].lstrip('</td>').rstrip('</td>')

        e = Event()
        if ('-' in week):
            week = week.split('-')
            #print(week)
            week_cur = int(week[0])
            week_end = int(week[1])
            while week_cur <= week_end:
                e = Event()
                e.name = course_name
                e.location = local
                e.description = remark
                offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                            hours=self.start_h[int(time[0])],
                                            minutes=self.start_m[int(time[0])])
                e.begin = self.term_start_time + offset
                offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                            hours=self.end_h[int(time[1])],
                                            minutes=self.end_m[int(time[1])])
                e.end = self.term_start_time + offset
                week_cur += 1
                self.c.events.add(e)
        else:
            week = week.split(',')
            #print(week)
            for we in week:
                e = Event()
                e.name = course_name
                e.location = local
                e.description = remark
                offset = datetime.timedelta(days=(int(we) - 1) * 7 + weekday,
                                            hours=self.start_h[int(time[0])],
                                            minutes=self.start_m[int(time[0])])
                e.begin = self.term_start_time + offset
                offset = datetime.timedelta(days=(int(we) - 1) * 7 + weekday,
                                            hours=self.end_h[int(time[1])],
                                            minutes=self.end_m[int(time[1])])
                e.end = self.term_start_time + offset
                self.c.events.add(e)
Exemple #5
0
def get_events(item):
    time_table = [
        [8, 30],  #1
        [10, 20],  #3
        [14, 30],  #5
        [16, 20],  #7
        [19, 30]  #9
    ]
    course_long = [0, 0, 95, 145, 205]
    begin_time = time_table[item['begin_time'] // 2]

    event_list = []
    for i in range(item['begin_week'], item['end_week'] + 1):
        b_time = datetime(2019, 9, 2, begin_time[0], begin_time[1],
                          0) + timedelta(
                              hours=-8, days=item['week'] - 1, weeks=i - 1)
        e_time = b_time + timedelta(minutes=course_long[item['num']])
        ##print(b_time,'-------',e_time)
        e = Event()
        e.name = item['name']
        e.location = item['location']
        e.begin = str(b_time)
        e.end = str(e_time)
        event_list.append(e)
    return event_list
Exemple #6
0
    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()
Exemple #7
0
def create_ical_event_from_session(session):
    e = Event()
    e.name = session.title
    e.begin = session.start_time
    e.end = session.end_time
    e.location = session.location
    return e
 def exportClass(self, day):
     e = Event()
     e.name = self.name
     e.begin = datetime.combine(day, self.begin) + timedelta(hours=4)
     e.end = datetime.combine(day, self.end) + timedelta(hours=4)
     e.location = self.location
     return (e)
Exemple #9
0
def main(args):
    res = requests.get('http://www.febclub2017.com/events')
    print "Encoding: {}".format(res.encoding)
    soup = BeautifulSoup(res.text, 'html.parser')

    cal = Calendar()

    for link in soup.find_all("div", { "class" : "detail" }):
        # Parse and format data
        paragraphs = [p.text for p in link.find_all('p')]
        date = paragraphs[2].split('\n')

        start_date = dp.parse("{} {}".format(date[0], date[1].split('-')[0].strip()))
        end_date = dp.parse("{} {}".format(date[0], date[1].split('-')[1].strip()))

        if end_date < start_date:
            end_date = end_date + timedelta(days=1)

        start_date = pytz.timezone('US/Eastern').localize(start_date)
        end_date = pytz.timezone('US/Eastern').localize(end_date)

        description = paragraphs[1].encode('ascii', errors='backslashreplace')

        event = Event()
        event.name = link.h1.text
        event.begin = start_date.isoformat()
        event.end = end_date.isoformat()
        event.description = u"{}\n{}\n\n{}".format(paragraphs[0], paragraphs[4], description)
        event.location = paragraphs[3]

        cal.events.append(event)
        print "Added event {}".format(link.h1.text)

    with open('febclub.ics', 'w') as f:
        f.writelines(cal)
Exemple #10
0
    def loadCal(self):
        with open("CAL_REQ.json", "r") as f:
            global c
            c2 = Calendar()
            data = json.load(f)
            headers = {"Authorization": "basic T64Mdy7m["}
            r = requests.post(
                "https://opentimetable.dcu.ie/broker/api/categoryTypes/241e4d36-60e0-49f8-b27e-99416745d98d/categories/events/filter",
                json=data,
                headers=headers,
            )
            if r.status_code == 200:
                response = json.loads(r.text)
                for event in response[0]["CategoryEvents"]:
                    e = Event()
                    e.begin = event["StartDateTime"]
                    e.end = event["EndDateTime"]
                    e.location = event["Location"]
                    e.description = ""
                    for item in event["ExtraProperties"]:
                        if item["DisplayName"] == "Module Name":
                            e.name = "{} - {}".format(item["Value"],
                                                      event["EventType"])
                        e.description += "{}: {}\n".format(
                            item["DisplayName"], item["Value"])

                    c2.events.add(e)
                c = c2
                return True
            else:
                print("Request Failed: %d" % r.status_code)
                return False
Exemple #11
0
def make(parsed, monday):
    calendar = Calendar()
    calendar.creator = "eAUrnik - Fork me on GitHub: https://git.io/JO5Za"
    
    durations = []
    for duration in parsed[0]:
        start, end = duration.split(" - ")
        start_hours, start_minutes = map(int, start.split(":"))
        end_hours, end_minutes = map(int, end.split(":"))
        durations.append(((start_hours, start_minutes), (end_hours, end_minutes)))
        
    data = parsed[1]
    for day_index in range(0, len(data)):
        day = monday + timedelta(days = day_index)
        lessons = data[day_index]
        for lesson_index in range(0, len(lessons)):
            for lesson in lessons[lesson_index]:
                title = lesson[0]
                subtitle = lesson[1]
                
                duration = durations[lesson_index]
                timezone = ZoneInfo("Europe/Ljubljana")
                start = datetime(day.year, day.month, day.day, duration[0][0], duration[0][1], tzinfo = timezone)
                end = datetime(day.year, day.month, day.day, duration[1][0], duration[1][1], tzinfo = timezone)

                event = Event()
                event.name = title
                event.location = subtitle
                event.begin = start
                event.end = end
                calendar.events.add(event)

    return string(calendar)
Exemple #12
0
def send_appointment_reminder(signup: AppointmentSignup):
    appointment = signup.appointment
    user = signup.user

    c = Calendar()
    e = Event()
    e.name = f"{format_coursecode(get_course())} Appointment"
    e.begin = pytz.timezone("America/Los_Angeles").localize(appointment.start_time)
    e.end = e.begin + appointment.duration
    e.location = appointment.location.name
    c.events.add(e)

    helper_msg = (
        f"It will be led by {appointment.helper.name}.\n" if appointment.helper else ""
    )

    send_email(
        sender="OH Queue <*****@*****.**>",
        target=user.email,
        subject=f"{format_coursecode(get_course())} Appointment Scheduled",
        body=(
            f"""
    Hi {user.short_name},

    An appointment has been scheduled for you using the {format_coursecode(get_course())} OH Queue. 
    It is at {appointment.start_time.strftime('%A %B %-d, %I:%M%p')} Pacific Time, at location {appointment.location.name}.
    {helper_msg}
    To edit or cancel this appointment, go to https://{get_domain()}.

    Best,
    The 61A Software Team
    """.strip()
        ),
        attachments={"invite.ics": b64encode(str(c).encode("utf-8")).decode("ascii")},
    )
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))
Exemple #14
0
def CreateCalendar(groups, Classes, periods):
    global NbEventsCreated
    cal = Calendar()
    dateFormat = "%Y-%m-%d %H:%M:%S"
    for period in periods:
        FirstWeekDay = period[0].weekday()
        LastWeekDay = period[1].weekday()
        for i in range(FirstWeekDay, LastWeekDay + 1):
            for Class in Classes:
                if Class[2] == i:
                    if Class[5] == 1 or getGroupOfClass(
                            groups, Classes.index(Class)
                    ) == period[
                            2]:  #if frequency is 1 (class occuring each week) or if group matches period
                        e = Event()
                        startDT = period[0] + timedelta(Class[2] -
                                                        period[0].weekday())
                        startDT = startDT.replace(
                            hour=int(Class[3][:Class[3].index(':')]))
                        startDT = startDT.replace(
                            minute=int(Class[3][Class[3].index(':') + 1:]))
                        endDT = startDT.replace(
                            hour=int(Class[4][:Class[4].index(':')]))
                        endDT = endDT.replace(
                            minute=int(Class[4][Class[4].index(':') + 1:]))
                        e.begin = startDT.strftime(dateFormat)
                        e.end = endDT.strftime(dateFormat)
                        e.location = Class[6]
                        e.name = Class[0] + " (" + Class[1] + ")"
                        cal.events.add(e)
                        NbEventsCreated += 1
    return cal
    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!')
Exemple #16
0
    def add_session(self, session):
        e = Event()
        e.name = session.name
        e.begin = session.begin
        e.duration = session.duration
        e.location = session.location

        self.c.events.add(e)
Exemple #17
0
 def createICS(typ,deb,fin,matiere,salle,prof):
     e = Event()
     e.name = "{} - {}".format(salle,matiere)
     e.begin = deb
     e.end = fin
     e.location = salle
     e.description = "{}: {} en {} par {}".format(typ,matiere,salle,prof)
     self.c.events.add(e)
Exemple #18
0
 def AppendEvent():
     e = Event()
     e.name = kc[0]
     e.begin = d1.isoformat() + 'T' + st[int(kc[4]) - 1]
     e.end = d1.isoformat() + 'T' + et[int(kc[5]) - 1]
     e.location = kc[2]
     c.events.append(e)
     print('ok')
     return
Exemple #19
0
 def convert_to_event(self):
     for period in self.__class_list:
         e = Event()
         e.name = period.name
         e.begin = period.ics_formatted_plus_eight_start
         e.end = period.ics_formatted_plus_eight_end
         e.location = period.location
         e.description = period.class_type
         self.__calendar.events.add(e)
Exemple #20
0
 def lesson_week_to_event(week: int):
     lesson_day = term_start_date + datetime.timedelta(days=lesson.day + (week - 1) * 7 - 1)
     begin_time, end_time = get_lesson_time(list(lesson.time))
     e = Event()
     e.name = lesson.name
     e.begin = arrow.get(datetime.datetime.combine(lesson_day, begin_time, local_tz))
     e.end = arrow.get(datetime.datetime.combine(lesson_day, end_time, local_tz))
     e.location = lesson.location
     e.description = lesson.remark
     return e
Exemple #21
0
    def add_event(event):
        e = Event()
        e.uid = str(event.get('calendar_key', event.get('id')))
        e.name = format_title(event)
        e.begin = event.get('timestamp', time.time())
        e.end = event.get('timestamp', time.time())
        e.description = format_desc(event)
        e.location = event.get('country', '')

        c.events.add(e)
Exemple #22
0
 def oneLessonToIcsEvent(self):
     e = Event()
     e.name = "({}){}".format(self.addressOfTheLesson, self.nameOfTheLesson)
     e.uid = self.oneLessonID
     e.description = "任课老师:{} \n 周数:{}".format(self.teacherNameOfTheLesson,
                                               self.__weeks)
     e.location = self.addressOfTheLesson
     e.begin = self.startTime
     e.end = self.endTime
     return e
Exemple #23
0
 def ics_event(self):
     e = Event()
     e.name = '{} {} Exam'.format(self.unit, self.subject)
     e.begin = self.start
     e.end = self.end
     e.location = self.venue
     e.url = URL
     e.description = 'Seat: {} \r\nConditions: {} \r\nDuration: {} minutes \r\nVenue: {}'.format(
         self.seat, self.conditions, self.duration, self.venue)
     return e
Exemple #24
0
    def create_ICS_event(self):
        ICS_event = ICS_Event()
        ICS_event.name = self.name
        ICS_event.begin = self.begin
        ICS_event.end = self.end
        ICS_event.location = self.location
        ICS_event.description = self.description
        ICS_event.categories = self.categories

        return ICS_event
Exemple #25
0
def generate_ical_for_job(job):
    c = Calendar()
    e = Event()
    e.name = Config.organisation_name() + ' Einsatz:' + job.type.name
    e.location = job.type.location
    e.description = job.type.description
    e.begin = job.time.strftime('%Y%m%d %H:%M:%S')
    e.end = job.time.strftime('%Y%m%d %H:%M:%S')
    c.events.append(e)
    return str(c).replace('\n', '\r\n') + '\r\n'
Exemple #26
0
 def to_ics(self):
     lessons = self.get_lessons()
     events = []
     for lesson in lessons:
         e = Event()
         e.name = self.course
         e.location = self.room
         e.begin = arrow.get(lesson[0] - timedelta(hours=7))
         e.end = arrow.get(lesson[1] - timedelta(hours=7))
         events.append(e)
     return events
Exemple #27
0
def build_ics(raceID, date_time, race_name, address):
    c = Calendar()
    e = Event()
    e.name = race_name
    e.location = address
    e.begin = date_time
    e.end = date_time + datetime.timedelta(hours=4)

    c.events.append(e)
    with open('./ics/{}.ics'.format(raceID), 'w') as my_file:
        my_file.writelines(c)
def add_course(time, name, weeks, weekflag, local, remark):
    if (len(weeks) != 2):
        for week in weeks:
            e = Event()
            e.name = name
            e.location = local
            e.description = remark
            offset = datetime.timedelta(days=(int(week) - 1) * 7 + weekday,
                                        hours=start_h[int(time[0])],
                                        minutes=start_m[int(time[0])])
            e.begin = term_start_time + offset
            #print(term_start_time + offset)
            offset = datetime.timedelta(days=(int(week) - 1) * 7 + weekday,
                                        hours=end_h[int(time[1])],
                                        minutes=end_m[int(time[1])])
            e.end = term_start_time + offset
            #print(term_start_time + offset)
            c.events.add(e)
        print("成功导入:", name, time, weeks, weekflag, local, remark)
    else:
        week_cur = int(weeks[0])
        week_end = int(weeks[1])
        while week_cur <= week_end:
            e = Event()
            e.name = name
            e.location = local
            e.description = remark
            offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                        hours=start_h[int(time[0])],
                                        minutes=start_m[int(time[0])])
            e.begin = term_start_time + offset
            #print(term_start_time + offset)
            offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                        hours=end_h[int(time[1])],
                                        minutes=end_m[int(time[1])])
            e.end = term_start_time + offset
            #print(term_start_time + offset)
            if (weekflag): week_cur += 2
            else: week_cur += 1
            c.events.add(e)
        print("成功导入:", name, time, weeks, weekflag, local)
Exemple #29
0
def CreateClassEvents(classn, dayn, classStr):
    events = []
    className = ''
    # print(name[0])
    if config.CONFIG['regexMode'] == 1:
        timeMatches = re.finditer(
            r'(?P<teachername>[\u4e00-\u9fa5 \t0-9()()]*?)\[(?P<begindate>\d*)-?(?P<enddate>\d*)\] ?周(</br>)?(?P<location>.*?)(?=$|,|,|</br>|<br/>)',
            classStr)
        className = re.findall(".*?(?=</br>)", classStr)
    elif config.CONFIG['regexMode'] == 2:
        timeMatches = re.finditer(
            r'(?P<teachername>[\u4e00-\u9fa5 \t0-9]*?)\[(?P<begindate>\d*)-?(?P<enddate>\d*)\] ?周(</br>)?(?P<location>.*)\n第(?P<classtime>[1-9,,]*)节',
            classStr)
        className = list(
            re.finditer(
                r'(?P<classname>[\u4e00-\u9fa5 \t0-9()()a-zA-Z]*?)</br>(?P<teachername>[\u4e00-\u9fa5 \t0-9]*?)\[(?P<begindate>\d*)-?(?P<enddate>\d*)\] ?周(</br>)?(?P<location>.*)\n',
                classStr))[0].groupdict()['classname']
    else:
        timeMatches = re.finditer(config.CONFIG['customRegex'], classStr)
    teacherName = ''
    print(className)
    for timeMatch in timeMatches:
        timeMatch = timeMatch.groupdict()
        print(timeMatch)
        rg = None
        class_begin_time = _CLASSTIME[classn][0]
        class_end_time = _CLASSTIME[classn][1]
        if 'classtime' in timeMatch.keys():
            (earliest,
             latest) = (int(timeMatch['classtime'].split(',')[0]) - 1,
                        int(timeMatch['classtime'].split(',')[-1]) - 1)
            class_begin_time = _CLASSTIME_SINGLE[earliest][0]
            class_end_time = _CLASSTIME_SINGLE[latest][1]
        if (timeMatch['teachername'] != ''):
            teacherName = timeMatch['teachername']
        if (timeMatch['enddate'] == ''):
            rg = range(int(timeMatch['begindate']),
                       int(timeMatch['begindate']) + 1)
        else:
            rg = range(int(timeMatch['begindate']),
                       int(timeMatch['enddate']) + 1)
        for i in rg:
            event = Event()
            event.name = className
            event.begin = CombineDateAndTime(GetWeekDate(BEGIN_DATE, i, dayn),
                                             class_begin_time)
            event.end = CombineDateAndTime(GetWeekDate(BEGIN_DATE, i, dayn),
                                           class_end_time)
            event.location = timeMatch['location']
            event.description = "讲师:" + teacherName
            events.append(event)
    print('--------')
    return events
Exemple #30
0
def parse_event(event):
    new_event = Event()

    new_event.name = event.find('h3', attrs={
        'class': 'card__title'
    }).getText().strip()
    new_event.location = event.findAll('p')[1].getText().strip()
    times = event.findAll('time')

    new_event.begin = arrow.get(times[1]['datetime'])
    new_event.end = arrow.get(times[2]['datetime'])

    return new_event
Exemple #31
0
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 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)
# 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()
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:
			print grow
			raise
# END for grow

# Write ics file to disk
with codecs.open("lacnic27.ics", "w", encoding="utf-8") as fn:
    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)
            

Exemple #36
0
            #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)
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