当前位置: 首页>>代码示例>>Python>>正文


Python icalendar.Event方法代码示例

本文整理汇总了Python中icalendar.Event方法的典型用法代码示例。如果您正苦于以下问题:Python icalendar.Event方法的具体用法?Python icalendar.Event怎么用?Python icalendar.Event使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在icalendar的用法示例。


在下文中一共展示了icalendar.Event方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write_ical

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def write_ical(events, year, dataDir):
    # write iCal
    cal = Calendar()

    for awesomeEvent in events:
        event = Event()

        event.add('summary', awesomeEvent.title)
        event.add('dtstart', date.fromisoformat(awesomeEvent.startDate))
        event.add('dtend', date.fromisoformat(
            awesomeEvent.endDate) + timedelta(days=1))
        event.add('description',
                  f'{awesomeEvent.description} - {awesomeEvent.url}')
        event.add('location', awesomeEvent.location)
        cal.add_component(event)

    with open(f'{dataDir}{year}.ics', 'wb') as ics:
        ics.write(cal.to_ical()) 
开发者ID:ildoc,项目名称:awesome-italy-events,代码行数:20,代码来源:generate_data.py

示例2: _build_event

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def _build_event(card_name: str, times: Tuple[datetime, datetime], classroom: str, teacher: str, current_week: int,
                 week_string: str, cid: str) -> Event:
    """
    生成 `Event` 对象

    :param card_name: 课程名
    :param times: 开始和结束时间
    :param classroom: 课程地点
    :param teacher: 任课教师
    :return: `Event` 对象
    """

    event = Event()
    event.add('transp', 'TRANSPARENT')
    summary = card_name
    if classroom != 'None':
        summary = card_name + '@' + classroom
        event.add('location', classroom)

    description = week_string
    if teacher != 'None':
        description += '\n教师:' + teacher
    description += '\n由 EveryClass 每课 (https://everyclass.xyz) 导入'

    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', times[0])
    event.add('dtend', times[1])
    event.add('last-modified', datetime.now())

    # 使用"cid-当前周"作为事件的超码
    event_sk = cid + '-' + str(current_week)
    event['uid'] = hashlib.md5(event_sk.encode('utf-8')).hexdigest() + '@everyclass.xyz'
    alarm = Alarm()
    alarm.add('action', 'none')
    alarm.add('trigger', datetime(1980, 1, 1, 3, 5, 0))
    event.add_component(alarm)
    return event 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:40,代码来源:ics_generator.py

示例3: has_event

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def has_event(dt):
    if ics is None:
        return False

    for item in ics.walk():
        if isinstance(item, icalendar.Event):
            dtstart = item['DTSTART'].dt
            dtend = item['DTEND'].dt
            summary = item['SUMMARY']

            if dt >= dtstart and dt < dtend:
                return True

    return False 
开发者ID:pimoroni,项目名称:inky-phat,代码行数:16,代码来源:cal-ics.py

示例4: generate_icalendar_element

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def generate_icalendar_element(event):
    icalendar_event = CalendarEvent()
    if event.start_time:
        icalendar_event.add('dtstart', event.start_time)
    if event.end_time:
        icalendar_event.add('dtend', event.end_time)
    if event.name_en:
        icalendar_event.add('summary', event.name_en)

    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//events.hel.fi//NONSGML Feeder//EN')
    cal.add_component(icalendar_event)

    term = None
    if event.start_time and event.end_time:
        term = "open"
    elif event.start_time:
        term = "open"
    elif event.end_time:
        term = "close"

    if term:
        return {
            "term": "open",
            "value": cal.to_ical().decode('utf8'),
            "type": "text/icalendar"
        }
    else:
        return None 
开发者ID:City-of-Helsinki,项目名称:linkedevents,代码行数:32,代码来源:city_sdk.py

示例5: write_items

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def write_items(self, calendar):
        """
        Write all events to the calendar
        """
        for item in self.items:
            event = Event()
            for ifield, efield in ITEM_EVENT_FIELD_MAP:
                val = item.get(ifield)
                if val is not None:
                    if ifield == "attendee":
                        for list_item in val:
                            event.add(efield, list_item)
                    else:
                        event.add(efield, val)
            calendar.add_component(event) 
开发者ID:jazzband,项目名称:django-ical,代码行数:17,代码来源:feedgenerator.py

示例6: schedule2calendar

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def schedule2calendar(schedule, name='课表', using_todo=True):
    """
    将上课时间表转换为 icalendar

    :param schedule: 上课时间表
    :param name: 日历名称
    :param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
    :return: icalendar.Calendar()
    """
    # https://zh.wikipedia.org/wiki/ICalendar
    # http://icalendar.readthedocs.io/en/latest
    # https://tools.ietf.org/html/rfc5545
    cal = icalendar.Calendar()
    cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')
    cal.add('X-WR-CALNAME', name)
    cls = icalendar.Todo if using_todo else icalendar.Event
    for week, start, end, data in schedule:
        # "事件"组件更具通用性, Google 日历不支持"待办"组件
        item = cls(
            SUMMARY='第{:02d}周-{}'.format(week, data),
            DTSTART=icalendar.vDatetime(start),
            DTEND=icalendar.vDatetime(end),
            DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M'))
        )
        now = datetime.now()
        # 这个状态"事件"组件是没有的, 对于待办列表类应用有作用
        # https://tools.ietf.org/html/rfc5545#section-3.2.12
        if using_todo:
            if start < now < end:
                item.add('STATUS', 'IN-PROCESS')
            elif now > end:
                item.add('STATUS', 'COMPLETED')
        cal.add_component(item)
    return cal 
开发者ID:elonzh,项目名称:hfut,代码行数:36,代码来源:curriculum_calendar.py

示例7: get

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def get(self, request, *args, **kwargs):
        document_id = request.GET.get('document_id')
        if not document_id:
            return JsonResponse({'error': "Document id is not defined."})

        sample_length = 100
        # Create calendar
        cal = icalendar.Calendar()
        cal.add('prodid', 'ContraxSuite (https://contraxsuite.com)')
        cal.add('version', settings.VERSION_NUMBER)

        # Filter to text unit
        for du in self.get_queryset():
            event = icalendar.Event()
            event.add("summary", "Calendar reminder for document {0}, text unit {1}:\n{2}"
                      .format(du.text_unit.document.name, du.text_unit_id,
                              du.text_unit.text[:sample_length]))
            event.add("dtstart", du.date)
            event.add("dtend", du.date)
            event.add("dtstamp", du.date)
            cal.add_component(event)

        filename = "document-{0}.ics".format(document_id)

        response = HttpResponse(cal.to_ical(), content_type='text/calendar; charset=utf8')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response


# --------------------------------------------------------
# Date Duration Usage Views
# -------------------------------------------------------- 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:34,代码来源:v1.py

示例8: get

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def get(self, request, *args, **kwargs):
        document_pk = request.GET.get('document_pk')
        if not document_pk:
            return Http404("Document pk is not defined.")

        sample_length = 100
        # Create calendar
        cal = icalendar.Calendar()
        cal.add('prodid', 'ContraxSuite (https://contraxsuite.com)')
        cal.add('version', '1.0.3')

        # Filter to text unit
        for du in self.get_json_data()['data']:
            event = icalendar.Event()
            event.add("summary", "Calendar reminder for document {0}, text unit {1}:\n{2}"
                      .format(du['document__name'], du['text_unit_id'],
                              du['text_unit__textunittext__text'][:sample_length]))
            event.add("dtstart", du['date'])
            event.add("dtend", du['date'])
            event.add("dtstamp", du['date'])
            cal.add_component(event)

        filename = "document-{0}.ics".format(document_pk)

        response = HttpResponse(cal.to_ical(), content_type='text/calendar; charset=utf8')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:29,代码来源:views.py

示例9: get_calendar

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def get_calendar(assessment):
    """
    Returns a compiled calendar containing the given assessment.
    """
    calendar = Calendar()
    for assessment_item in assessment:
        course, task, due_date, weight = assessment_item
        event = Event()
        event['uid'] = str(uuid())
        event['summary'] = f'{course} ({weight}): {task}'
        try:
            start_datetime, end_datetime = get_parsed_assessment_due_date(assessment_item)
        except DateSyntaxException as e:
            bot.logger.error(e.message)
            # If we can't parse a date, set its due date to today
            # and let the user know through its summary.
            # TODO(mitch): Keep track of these instances to attempt to accurately
            # parse them in future. Will require manual detection + parsing.
            start_datetime = end_datetime = datetime.today()
            event['summary'] = ("WARNING: DATE PARSING FAILED\n"
                                "Please manually set date for event!\n"
                                "The provided due date from UQ was"
                                + f" '{due_date}\'. {event['summary']}")
        event.add('dtstart', start_datetime)
        event.add('dtend', end_datetime)
        calendar.add_component(event)
    return calendar.to_ical() 
开发者ID:UQComputingSociety,项目名称:uqcsbot,代码行数:29,代码来源:calendar.py

示例10: _as_ics

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def _as_ics(self, citymeo=False):
        if not self.initialized:
            self._lazy_init()
        cal = iCalendar()
        cal.add('prodid', '-//PonyConf.io//PonyConf//FR')
        cal.add('version', '2.0')
        cal.add('x-wr-calname', self.conference.name)
        cal.add('x-wr-timezone', settings.TIME_ZONE)
        cal.add('calscale', 'GREGORIAN')
        talks = self.talks
        if citymeo and talks.exists():
            talks = talks.filter(start_date__gte=now()-timedelta(minutes=5))
            if talks.exists():
                limit = talks.first().start_date.replace(hour=23, minute=59, second=59)
                talks = talks.filter(start_date__lte=limit)
        for talk in talks:
            event = iEvent()
            event.add('dtstart', talk.start_date)
            if not talk.end_date:
                continue
            event.add('dtend', talk.end_date)
            event.add('dtstamp', talk.updated)
            event.add('summary', talk.title)
            if talk.room:
                event.add('location', talk.room)
            event.add('status', 'CONFIRMED' if talk.accepted else 'TENTATIVE')
            if not citymeo:
                event.add('description', talk.description)
            event.add('uid', '%s/%s' % (self.site.domain, talk.id))
            cal.add_component(event)
        return cal.to_ical() 
开发者ID:PonyConf,项目名称:PonyConf,代码行数:33,代码来源:planning.py

示例11: build_event_duration

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def build_event_duration(summary, description, start, duration, location,
        freq_of_recurrence, until):

    '''
    Return an event that can be added to a calendar

    summary: summary of the event
    description: description of the event
    location: self explanatory
    start, end, stamp: These are datetime.datetime objects
    freq_of_recurrence: frequency of recurrence, string which can take the
    values daily, weekly, monthly, etc.
    until: A datetime.datetime object which signifies when the recurrence will
    end
    '''

    event = Event()
    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', start)
    event.add('duration', timedelta(hours=duration))
    event.add('dtstamp', datetime.now())
    event.add('location', location)
    event.add('rrule', { 'FREQ': freq_of_recurrence, 'UNTIL': until})

    return event 
开发者ID:metakgp,项目名称:gyft,代码行数:28,代码来源:build_event.py

示例12: calendar_ical

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def calendar_ical(request, token, userid):
    """
    Return an iCalendar for this user, authenticated by the token in the URL
    """
    local_tz = pytz.timezone(settings.TIME_ZONE)
    utc = pytz.utc
    user = get_object_or_404(Person, userid=userid)
    
    # make sure the token in the URL (32 hex characters) matches the token stored in the DB
    config = _get_calendar_config(user)
    if 'token' not in config or config['token'] != token:
        # no token set or wrong token provided
        return NotFoundResponse(request)
    #else:
        # authenticated

    now = datetime.datetime.now()
    start = local_tz.localize(now - datetime.timedelta(days=180))
    end = local_tz.localize(now + datetime.timedelta(days=365))
    
    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//SFU CourSys//courses.cs.sfu.ca//')
    cal.add('X-PUBLISHED-TTL', 'PT1D')
    
    for data in _calendar_event_data(user, start, end, local_tz, dt_string=False):
        e = Event()
        e['uid'] = str(data['id'])
        e.add('summary', data['title'])
        e.add('dtstart', _ical_datetime(utc, data['start']))
        e.add('dtend', _ical_datetime(utc, data['end']))
        if data['category'] in ('DUE', 'HOLIDAY'):
            # these shouldn't be "busy" on calendars
            e.add('transp', 'TRANSPARENT')
        else:
            e.add('transp', 'OPAQUE')

        # spec says no TZID on UTC times
        if 'TZID' in e['dtstart'].params:
            del e['dtstart'].params['TZID']
        if 'TZID' in e['dtend'].params:
            del e['dtend'].params['TZID']
        
        e.add('categories', data['category'])
        if 'url' in data:
            e.add('url', data['url'])
        if 'location' in data:
            e.add('location', data['location'])
        cal.add_component(e)

    resp = HttpResponse(cal.to_ical(), content_type="text/calendar")
    return resp 
开发者ID:sfu-fas,项目名称:coursys,代码行数:54,代码来源:views.py

示例13: ical_from_pairings_list

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def ical_from_pairings_list(self, pairings, calendar_title, uid_component):
        cal = Calendar()
        cal.add('prodid', '-//{}//www.lichess4545.com//'.format(calendar_title))
        cal.add('version', '2.0')

        has_league = hasattr(self, 'league')
        league = self.league if has_league else None

        for pairing in pairings:
            if not has_league:
                round_ = pairing.get_round()
                if not round_:
                    continue
                league = round_.season.league
            time_control_seconds = league.time_control_total()
            if time_control_seconds:
                game_duration = timedelta(seconds=time_control_seconds * 2)
            else:
                game_duration = timedelta(hours=3)

            ical_event = Event()
            ical_event.add('summary', '{} vs {}'.format(
                pairing.white.lichess_username,
                pairing.black.lichess_username,
            ))
            ical_event.add('dtstart', pairing.scheduled_time)
            ical_event.add('dtend', pairing.scheduled_time + game_duration)
            ical_event.add('dtstamp', pairing.scheduled_time + game_duration)
            ical_event['uid'] = 'lichess4545.{}.events.{}'.format(
                uid_component,
                pairing.id,
            )
            cal.add_component(ical_event)

        response = HttpResponse(cal.to_ical(), content_type="text/calendar")
        response['Content-Disposition'] = 'attachment; filename={}.ics'.format(
            slugify(calendar_title)
        )
        return response


# -------------------------------------------------------------------------------
# Actual views 
开发者ID:cyanfish,项目名称:heltour,代码行数:45,代码来源:views.py

示例14: process_invites

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def process_invites(db_session, message, account, invites):
    new_uids = [event.uid for event in invites]

    # Get the list of events which share a uid with those we received.
    # Note that we're limiting this query to events in the 'emailed events'
    # calendar, because that's where all the invites go.
    existing_events = db_session.query(Event).filter(
        Event.calendar_id == account.emailed_events_calendar_id,
        Event.namespace_id == account.namespace.id,
        Event.uid.in_(new_uids)).all()

    existing_events_table = {event.uid: event for event in existing_events}

    for event in invites:
        if event.uid not in existing_events_table:
            # This is some SQLAlchemy trickery -- the events returned
            # by events_from_ics aren't bound to a session yet. Because of
            # this, we don't care if they get garbage-collected. This is
            # important because we only want to keep events we haven't seen
            # yet --- updates are merged with the existing events and are
            # dropped immediately afterwards.
            # By associating the event to the message we make sure it
            # will be flushed to the db.
            event.calendar = account.emailed_events_calendar
            event.message = message
        else:
            # This is an event we already have in the db.
            # Let's see if the version we have is older or newer.
            existing_event = existing_events_table[event.uid]

            if existing_event.sequence_number <= event.sequence_number:
                merged_participants = existing_event.\
                    _partial_participants_merge(event)

                existing_event.update(event)
                existing_event.message = message

                # We have to do this mumbo-jumbo because MutableList does
                # not register changes to nested elements.
                # We could probably change MutableList to handle it (see:
                # https://groups.google.com/d/msg/sqlalchemy/i2SIkLwVYRA/mp2WJFaQxnQJ)
                # but this sounds very brittle.
                existing_event.participants = []
                for participant in merged_participants:
                    existing_event.participants.append(participant) 
开发者ID:nylas,项目名称:sync-engine,代码行数:47,代码来源:ical.py

示例15: process_nylas_rsvps

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Event [as 别名]
def process_nylas_rsvps(db_session, message, account, rsvps):
    # The invite sending code generates invites with uids of the form
    # `public_id@nylas.com`. We couldn't use Event.uid for this because
    # it wouldn't work with Exchange (Exchange uids are of the form
    # 1:2323 and aren't guaranteed to be unique).
    new_uids = [_cleanup_nylas_uid(event.uid) for event in rsvps
                if '@nylas.com' in event.uid]

    # Drop uids which aren't base36 uids.
    new_uids = [uid for uid in new_uids if valid_base36(uid)]

    # Get the list of events which share a uid with those we received.
    # Note that we're excluding events from "Emailed events" because
    # we don't want to process RSVPs to invites we received.
    existing_events = db_session.query(Event).filter(
        Event.namespace_id == account.namespace.id,
        Event.calendar_id != account.emailed_events_calendar_id,
        Event.public_id.in_(new_uids)).all()

    existing_events_table = {event.public_id: event
                             for event in existing_events}

    for event in rsvps:
        event_uid = _cleanup_nylas_uid(event.uid)
        if event_uid not in existing_events_table:
            # We've received an RSVP to an event we never heard about. Save it,
            # maybe we'll sync the invite later.
            event.message = message
        else:
            # This is an event we already have in the db.
            existing_event = existing_events_table[event_uid]

            # Is the current event an update?
            if existing_event.sequence_number == event.sequence_number:
                merged_participants = existing_event.\
                    _partial_participants_merge(event)

                # We have to do this mumbo-jumbo because MutableList does
                # not register changes to nested elements.
                # We could probably change MutableList to handle it (see:
                # https://groups.google.com/d/msg/sqlalchemy/i2SIkLwVYRA/mp2WJFaQxnQJ)
                # but it seems very brittle.
                existing_event.participants = []
                for participant in merged_participants:
                    existing_event.participants.append(participant)

                # We need to sync back changes to the event manually
                if existing_event.calendar != account.emailed_events_calendar:
                    schedule_action('update_event', existing_event,
                                    existing_event.namespace.id, db_session,
                                    calendar_uid=existing_event.calendar.uid)

                db_session.flush() 
开发者ID:nylas,项目名称:sync-engine,代码行数:55,代码来源:ical.py


注:本文中的icalendar.Event方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。