Python get calendar

60 Python code examples are found related to " get calendar". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: service.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def get_calendar_token(resource_type: str, identifier: str, semester: str) -> str:
    """获取一个有效的日历订阅 token。

    如果找到了可用token则直接返回 token。找不到则生成一个再返回 token"""
    if resource_type == "student":
        token_doc = find_token(sid=identifier, semester=semester)
    else:
        token_doc = find_token(tid=identifier, semester=semester)

    if not token_doc:
        if resource_type == "student":
            token = insert_calendar_token(resource_type="student",
                                          identifier=identifier,
                                          semester=semester)
        else:
            token = insert_calendar_token(resource_type="teacher",
                                          identifier=identifier,
                                          semester=semester)
    else:
        token = token_doc['token']
    return token 
Example 2
Source File: client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def get_calendar_acl_feed(self, uri='https://www.google.com/calendar/feeds/default/acl/full',
                            desired_class=gdata.calendar.data.CalendarAclFeed,
                            auth_token=None, **kwargs):
    """Obtains an Access Control List feed.

    Args:
      uri: The uri of the desired Acl feed.
           Defaults to https://www.google.com/calendar/feeds/default/acl/full.
      desired_class: class descended from atom.core.XmlElement to which a
                     successful response should be converted. If there is no
                     converter function specified (desired_class=None) then the
                     desired_class will be used in calling the
                     atom.core.parse function. If neither
                     the desired_class nor the converter is specified, an
                     HTTP reponse object will be returned. Defaults to
                     gdata.calendar.data.CalendarAclFeed.
      auth_token: An object which sets the Authorization HTTP header in its
                  modify_request method. Recommended classes include
                  gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                  among others. Represents the current user. Defaults to None
                  and if None, this method will look for a value in the
                  auth_token member of SpreadsheetsClient.
    """
    return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class,
                         **kwargs) 
Example 3
Source File: addressmapping.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def getCalendarUserServiceType(self, cuaddr):

        # Try cache first
        cuaddr_type = (yield self.cache.get(str(cuaddr)))
        if cuaddr_type is None:

            serviceTypes = (ScheduleViaCalDAV,)
            if config.Scheduling[DeliveryService.serviceType_ischedule]["Enabled"]:
                serviceTypes += (ScheduleViaISchedule,)
            if config.Scheduling[DeliveryService.serviceType_imip]["Enabled"]:
                serviceTypes += (ScheduleViaIMip,)
            for service in serviceTypes:
                matched = (yield service.matchCalendarUserAddress(cuaddr))
                if matched:
                    yield self.cache.set(str(cuaddr), service.serviceType())
                    returnValue(service.serviceType())

        returnValue(cuaddr_type) 
Example 4
Source File: home_sync.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def getCalendarSyncList(self, txn):
        """
        Get the names and sync-tokens for each remote owned calendar.
        """

        # List of calendars from the remote side
        home = yield self._remoteHome(txn)
        if home is None:
            returnValue(None)
        calendars = yield home.loadChildren()
        results = {}
        for calendar in calendars:
            if calendar.owned():
                sync_token = yield calendar.syncToken()
                results[calendar.id()] = CalendarMigrationRecord.make(
                    calendarHomeResourceID=home.id(),
                    remoteResourceID=calendar.id(),
                    localResourceID=0,
                    lastSyncToken=sync_token,
                )

        returnValue(results) 
Example 5
Source File: purge.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def getCalendar(self, txn, resid):
        """
        Get the calendar data for a calendar object resource.

        @param resid: resource-id of the calendar object resource to load
        @type resid: L{int}
        """
        co = schema.CALENDAR_OBJECT
        kwds = {"ResourceID": resid}
        rows = (yield Select(
            [co.ICALENDAR_TEXT],
            From=co,
            Where=(
                co.RESOURCE_ID == Parameter("ResourceID")
            ),
        ).on(txn, **kwds))
        try:
            caldata = Component.fromString(rows[0][0]) if rows else None
        except InvalidICalendarDataError:
            returnValue(None)

        returnValue(caldata) 
Example 6
Source File: calverify.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def getCalendarForOwnerByUID(self, owner, uid):
        co = schema.CALENDAR_OBJECT
        cb = schema.CALENDAR_BIND
        ch = schema.CALENDAR_HOME

        kwds = {"OWNER": owner, "UID": uid}
        rows = (yield Select(
            [co.ICALENDAR_TEXT, co.RESOURCE_ID, co.CREATED, co.MODIFIED, ],
            From=ch.join(
                cb, type="inner", on=(ch.RESOURCE_ID == cb.CALENDAR_HOME_RESOURCE_ID)).join(
                co, type="inner", on=(cb.CALENDAR_RESOURCE_ID == co.CALENDAR_RESOURCE_ID).And(
                    cb.BIND_MODE == _BIND_MODE_OWN).And(
                    cb.CALENDAR_RESOURCE_NAME != "inbox")),
            Where=(ch.OWNER_UID == Parameter("OWNER")).And(co.ICALENDAR_UID == Parameter("UID")),
        ).on(self.txn, **kwds))

        try:
            caldata = Calendar.parseText(rows[0][0]) if rows else None
        except ErrorBase:
            returnValue((None, None, None, None,))

        returnValue((caldata, rows[0][1], rows[0][2], rows[0][3],) if rows else (None, None, None, None,)) 
Example 7
Source File: calendar.py    From my-dev-space with MIT License 6 votes vote down vote up
def get_all_calendar():
    """Get all calendar"""
    location = request.args.get("location", "belfast", type=str)
    location = location.lower()

    current_time = datetime.utcnow()
    recent_past = current_time - timedelta(hours=6)

    events = Event.query.filter(
        and_(Event.location == location, Event.start >= recent_past)
    )

    response_object = {
        "status": "success",
        "data": [_transform(index, event) for index, event in enumerate(events)],
    }
    return jsonify(response_object), 200 
Example 8
Source File: client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def get_calendar_event_feed_uri(self, calendar='default', visibility='private',
                                  projection='full', scheme="https"):
    """Builds a feed URI.

    Args:
      projection: The projection to apply to the feed contents, for example
        'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
      scheme: The URL scheme such as 'http' or 'https', None to return a
          relative URI without hostname.

    Returns:
      A feed URI using the given scheme and projection.
      Example: '/calendar/feeds/default/private/full'.
    """
    prefix = scheme and '%s://%s' % (scheme, self.server) or ''
    return '%s/calendar/feeds/%s/%s/%s' % (prefix, calendar,
                                           visibility, projection) 
Example 9
Source File: client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def get_calendar_feed_uri(self, feed='', projection='full', scheme="https"):
    """Builds a feed URI.

    Args:
      projection: The projection to apply to the feed contents, for example
        'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
      scheme: The URL scheme such as 'http' or 'https', None to return a
          relative URI without hostname.

    Returns:
      A feed URI using the given scheme and projection.
      Example: '/calendar/feeds/default/owncalendars/full'.
    """
    prefix = scheme and '%s://%s' % (scheme, self.server) or ''
    suffix = feed and '/%s/%s' % (feed, projection) or ''
    return '%s/calendar/feeds/default%s' % (prefix, suffix) 
Example 10
Source File: exchange_bundle.py    From catalyst with Apache License 2.0 6 votes vote down vote up
def get_calendar_periods_range(self, start_dt, end_dt, data_frequency):
        """
        Get a list of dates for the specified range.

        Parameters
        ----------
        start_dt: pd.Timestamp
        end_dt: pd.Timestamp
        data_frequency: str

        Returns
        -------
        list[datetime]

        """
        return self.calendar.minutes_in_range(start_dt, end_dt) \
            if data_frequency == 'minute' \
            else self.calendar.sessions_in_range(start_dt, end_dt) 
Example 11
Source File: client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def get_calendar_acl_entry(self, uri, desired_class=gdata.calendar.data.CalendarAclEntry,
                             auth_token=None, **kwargs):
    """Obtains a single Access Control List entry.

    Args:
      uri: The uri of the desired Acl feed.
      desired_class: class descended from atom.core.XmlElement to which a
                     successful response should be converted. If there is no
                     converter function specified (desired_class=None) then the
                     desired_class will be used in calling the
                     atom.core.parse function. If neither
                     the desired_class nor the converter is specified, an
                     HTTP reponse object will be returned. Defaults to
                     gdata.calendar.data.CalendarAclEntry.
      auth_token: An object which sets the Authorization HTTP header in its
                  modify_request method. Recommended classes include
                  gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                  among others. Represents the current user. Defaults to None
                  and if None, this method will look for a value in the
                  auth_token member of SpreadsheetsClient.
    """
    return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
                          **kwargs) 
Example 12
Source File: MicrosoftGraphCalendar.py    From content with MIT License 6 votes vote down vote up
def get_calendar_command(client: MsGraphClient, args: Dict) -> Tuple[str, Dict, Dict]:
    """
    Get the properties and relationships of a calendar object.
    The calendar can be one for a user, or the default calendar of an Office 365 group.

    Args:
        client: Client object with request
        args: Usually demisto.args()
    """
    calendar = client.get_calendar(**args)

    calendar_readable, calendar_outputs = parse_calendar(calendar)

    entry_context = {f'{INTEGRATION_CONTEXT_NAME}.Calendar(val.ID === obj.ID)': calendar_outputs}
    title = 'Calendar:'

    human_readable = tableToMarkdown(
        name=title,
        t=calendar_readable,
        headers=CALENDAR_HEADERS,
        removeNull=True
    )

    return human_readable, entry_context, calendar 
Example 13
Source File: api.py    From airbnb-python with Do What The F*ck You Want To Public License 6 votes vote down vote up
def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12):
        """
        Get availability calendar for a given listing
        """
        params = {
            'year': str(starting_year),
            'listing_id': str(listing_id),
            '_format': 'with_conditions',
            'count': str(calendar_months),
            'month': str(starting_month)
        }

        r = self._session.get(API_URL + "/calendar_months", params=params)
        r.raise_for_status()

        return r.json() 
Example 14
Source File: api.py    From airbnb-python with Do What The F*ck You Want To Public License 6 votes vote down vote up
def get_listing_calendar(self, listing_id, starting_date=datetime.datetime.now(), calendar_months=6):
        """
        Get host availability calendar for a given listing
        """
        params = {
            '_format': 'host_calendar_detailed'
        }

        starting_date_str = starting_date.strftime("%Y-%m-%d")
        end_days = calendar_months * 30
        ending_date_str = (
            starting_date + datetime.timedelta(days=end_days)).strftime("%Y-%m-%d")

        r = self._session.get(API_URL + "/calendars/{}/{}/{}".format(
            str(listing_id), starting_date_str, ending_date_str), params=params)
        r.raise_for_status()

        return r.json()

    # User past trips and stats 
Example 15
Source File: client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def get_calendar_entry(self, uri, desired_class=gdata.calendar.data.CalendarEntry,
                         auth_token=None, **kwargs):
    """Obtains a single calendar entry.

    Args:
      uri: The uri of the desired calendar entry.
      desired_class: class descended from atom.core.XmlElement to which a
                     successful response should be converted. If there is no
                     converter function specified (desired_class=None) then the
                     desired_class will be used in calling the
                     atom.core.parse function. If neither
                     the desired_class nor the converter is specified, an
                     HTTP reponse object will be returned. Defaults to
                     gdata.calendar.data.CalendarEntry.
      auth_token: An object which sets the Authorization HTTP header in its
                  modify_request method. Recommended classes include
                  gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                  among others. Represents the current user. Defaults to None
                  and if None, this method will look for a value in the
                  auth_token member of SpreadsheetsClient.
    """
    return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
                          **kwargs) 
Example 16
Source File: traktapi.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 6 votes vote down vote up
def get_calendar_properties(self, item, i):
        # Create our airing properties
        air_date = utils.convert_timestamp(i.get('first_aired'), utc_convert=True)
        item.infolabels['premiered'] = air_date.strftime('%Y-%m-%d')
        item.infolabels['year'] = air_date.strftime('%Y')
        item.infoproperties['air_date'] = utils.get_region_date(air_date, 'datelong')
        item.infoproperties['air_time'] = utils.get_region_date(air_date, 'time')
        item.infoproperties['air_day'] = air_date.strftime('%A')
        item.infoproperties['air_day_short'] = air_date.strftime('%a')
        item.infoproperties['air_date_short'] = air_date.strftime('%d %b')

        # Do some fallback properties in-case TMDb doesn't have info
        item.infolabels['title'] = item.label = i.get('episode', {}).get('title')
        item.infolabels['episode'] = item.infolabels.get('episode') or i.get('episode', {}).get('number')
        item.infolabels['season'] = item.infolabels.get('season') or i.get('episode', {}).get('season')
        item.infolabels['tvshowtitle'] = i.get('show', {}).get('title')
        item.infolabels['duration'] = item.infolabels.get('duration') or utils.try_parse_int(i.get('episode', {}).get('runtime', 0)) * 60
        item.infolabels['plot'] = item.infolabels.get('plot') or i.get('episode', {}).get('overview')
        item.infolabels['mpaa'] = item.infolabels.get('mpaa') or i.get('show', {}).get('certification')

        return item 
Example 17
Source File: schedule.py    From wechatpy with MIT License 6 votes vote down vote up
def get_by_calendar(self, calendar_id, offset=0, limit=500):
        """
        获取日历下的日程列表
        https://work.weixin.qq.com/api/doc/90000/90135/92626
        (注意,被取消的日程也可以拉取详情,调用者需要检查status)

        :param calendar_id: 日历ID
        :param offset: 分页,偏移量, 默认为0
        :param limit: 分页,预期请求的数据量,默认为500,取值范围 1 ~ 1000

        :return: 日程列表
        :rtype: list[dict]
        """
        return self._post(
            "oa/schedule/get_by_calendar",
            data={"cal_id": calendar_id, "offset": offset, "limit": limit},
            result_processor=op.itemgetter("schedule_list"),
        ) 
Example 18
Source File: torr2xbmc.py    From ru with GNU General Public License v2.0 6 votes vote down vote up
def getArchiveCalendar(params):
    res = re.compile('&data=.*')
    res.findall(params['file'])
    if res:
        date_site = res.findall(params['file'])[0].replace('&data=', '')
        #print date_site
        dt = datetime.datetime.fromtimestamp(time.mktime(time.strptime(date_site, '%d-%m-%Y')))
        #print dt
    for i in range(int(archive)):
        #date = datetime.datetime.now() - datetime.timedelta(days=i)
        date = dt - datetime.timedelta(days=i)
        date = date.timetuple()
        title = str(date.tm_mday) + '-' + str(date.tm_mon) + '-'  + str(date.tm_year)
        li = xbmcgui.ListItem(title)
        uri = construct_request({
            'func': 'getArchiveDate',
            'date': title,
            'file': params['file'],
            'img': params['img'],
        })
        xbmcplugin.addDirectoryItem(hos, uri, li, True)
    xbmcplugin.endOfDirectory(hos) 
Example 19
Source File: client.py    From gdata-python3 with Apache License 2.0 6 votes vote down vote up
def get_calendar_entry(self, uri, desired_class=gdata.calendar.data.CalendarEntry,
                           auth_token=None, **kwargs):
        """Obtains a single calendar entry.

        Args:
          uri: The uri of the desired calendar entry.
          desired_class: class descended from atom.core.XmlElement to which a
                         successful response should be converted. If there is no
                         converter function specified (desired_class=None) then the
                         desired_class will be used in calling the
                         atom.core.parse function. If neither
                         the desired_class nor the converter is specified, an
                         HTTP reponse object will be returned. Defaults to
                         gdata.calendar.data.CalendarEntry.
          auth_token: An object which sets the Authorization HTTP header in its
                      modify_request method. Recommended classes include
                      gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                      among others. Represents the current user. Defaults to None
                      and if None, this method will look for a value in the
                      auth_token member of SpreadsheetsClient.
        """
        return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
                              **kwargs) 
Example 20
Source File: client.py    From gdata-python3 with Apache License 2.0 6 votes vote down vote up
def get_calendar_acl_entry(self, uri, desired_class=gdata.calendar.data.CalendarAclEntry,
                               auth_token=None, **kwargs):
        """Obtains a single Access Control List entry.

        Args:
          uri: The uri of the desired Acl feed.
          desired_class: class descended from atom.core.XmlElement to which a
                         successful response should be converted. If there is no
                         converter function specified (desired_class=None) then the
                         desired_class will be used in calling the
                         atom.core.parse function. If neither
                         the desired_class nor the converter is specified, an
                         HTTP reponse object will be returned. Defaults to
                         gdata.calendar.data.CalendarAclEntry.
          auth_token: An object which sets the Authorization HTTP header in its
                      modify_request method. Recommended classes include
                      gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                      among others. Represents the current user. Defaults to None
                      and if None, this method will look for a value in the
                      auth_token member of SpreadsheetsClient.
        """
        return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
                              **kwargs) 
Example 21
Source File: client.py    From gdata-python3 with Apache License 2.0 6 votes vote down vote up
def get_calendar_feed_uri(self, feed='', projection='full', scheme="https"):
        """Builds a feed URI.

        Args:
          projection: The projection to apply to the feed contents, for example
            'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
          scheme: The URL scheme such as 'http' or 'https', None to return a
              relative URI without hostname.

        Returns:
          A feed URI using the given scheme and projection.
          Example: '/calendar/feeds/default/owncalendars/full'.
        """
        prefix = scheme and '%s://%s' % (scheme, self.server) or ''
        suffix = feed and '/%s/%s' % (feed, projection) or ''
        return '%s/calendar/feeds/default%s' % (prefix, suffix) 
Example 22
Source File: ml.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def get_calendar_events(self, calendar_id, params=None):
        """
        `<>`_

        :arg calendar_id: The ID of the calendar containing the events
        :arg end: Get events before this time
        :arg from_: Skips a number of events
        :arg job_id: Get events for the job. When this option is used
            calendar_id must be '_all'
        :arg size: Specifies a max number of events to get
        :arg start: Get events after this time
        """
        if calendar_id in SKIP_IN_PATH:
            raise ValueError(
                "Empty value passed for a required argument 'calendar_id'."
            )
        return self.transport.perform_request(
            "GET", _make_path("_ml", "calendars", calendar_id, "events"), params=params
        ) 
Example 23
Source File: date.py    From gprime with GNU General Public License v2.0 6 votes vote down vote up
def get_calendar(self):
        """
        Return an integer indicating the calendar selected.

        The valid values are:

        =============  ==========================================
        CAL_GREGORIAN  Gregorian calendar
        CAL_JULIAN     Julian calendar
        CAL_HEBREW     Hebrew (Jewish) calendar
        CAL_FRENCH     French Republican calendar
        CAL_PERSIAN    Persian calendar
        CAL_ISLAMIC    Islamic calendar
        CAL_SWEDISH    Swedish calendar 1700-03-01 -> 1712-02-30!
        =============  ==========================================
        """
        return self.calendar 
Example 24
Source File: date.py    From gprime with GNU General Public License v2.0 6 votes vote down vote up
def get_year_calendar(self, calendar_name=None):
        """
        Return the year of this date in the calendar name given.

        Defaults to self's calendar if one is not given.

        >>> Date(2009, 12, 8).to_calendar("hebrew").get_year_calendar()
        5770
        """
        if calendar_name:
            cal = lookup_calendar(calendar_name)
        else:
            cal = self.calendar
        if cal == self.calendar:
            return self.get_year()
        else:
            retval = Date(self)
            retval.convert_calendar(cal)
            return retval.get_year() 
Example 25
Source File: client.py    From gdata-python3 with Apache License 2.0 6 votes vote down vote up
def get_calendar_event_feed_uri(self, calendar='default', visibility='private',
                                    projection='full', scheme="https"):
        """Builds a feed URI.

        Args:
          projection: The projection to apply to the feed contents, for example
            'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
          scheme: The URL scheme such as 'http' or 'https', None to return a
              relative URI without hostname.

        Returns:
          A feed URI using the given scheme and projection.
          Example: '/calendar/feeds/default/private/full'.
        """
        prefix = scheme and '%s://%s' % (scheme, self.server) or ''
        return '%s/calendar/feeds/%s/%s/%s' % (prefix, calendar,
                                               visibility, projection) 
Example 26
Source File: __init__.py    From iexfinance with Apache License 2.0 6 votes vote down vote up
def get_ipo_calendar(period="upcoming-ipos", **kwargs):
    """IPO Calendar

    This returns a list of upcoming or today IPOs scheduled for the current and
    next month. The response is split into two structures: ``rawData`` and
    ``viewData``. ``rawData`` represents all available data for an IPO.
    ``viewData`` represents data structured for display to a user.

    Reference: https://iexcloud.io/docs/api/#ipo-calendar

    Data Weighting: ``100`` per IPO returned for ``upcoming-ipos``, ``500``
    returned for ``today-ipos``

    Parameters
    ----------
    period: str, default "upcoming-ipos", optional
        Desired period (options are "upcoming-ipos" and "today-ipos")
    """
    return IPOReader(period, **kwargs).fetch() 
Example 27
Source File: client.py    From gdata-python3 with Apache License 2.0 6 votes vote down vote up
def get_calendar_acl_feed(self, uri='https://www.google.com/calendar/feeds/default/acl/full',
                              desired_class=gdata.calendar.data.CalendarAclFeed,
                              auth_token=None, **kwargs):
        """Obtains an Access Control List feed.

        Args:
          uri: The uri of the desired Acl feed.
               Defaults to https://www.google.com/calendar/feeds/default/acl/full.
          desired_class: class descended from atom.core.XmlElement to which a
                         successful response should be converted. If there is no
                         converter function specified (desired_class=None) then the
                         desired_class will be used in calling the
                         atom.core.parse function. If neither
                         the desired_class nor the converter is specified, an
                         HTTP reponse object will be returned. Defaults to
                         gdata.calendar.data.CalendarAclFeed.
          auth_token: An object which sets the Authorization HTTP header in its
                      modify_request method. Recommended classes include
                      gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                      among others. Represents the current user. Defaults to None
                      and if None, this method will look for a value in the
                      auth_token member of SpreadsheetsClient.
        """
        return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class,
                             **kwargs) 
Example 28
Source File: settings.py    From lisflood-code with European Union Public License 1.2 5 votes vote down vote up
def get_calendar_type(nc):
    """Get the type of calendar of the open netCDF file passed as argument (http://cfconventions.org/)"""
    try:
        calendar_type = nc.variables["time"].calendar
    except AttributeError:
        calendar_type = "proleptic_gregorian"
        warnings.warn(LisfloodWarning("""
The 'calendar' attribute of the 'time' variable of {} is not set: the default '{}' is used
(http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.pdf)
""".format(nc, calendar_type)))
    return calendar_type 
Example 29
Source File: calendar_registry.py    From pandas_market_calendars with MIT License 5 votes vote down vote up
def get_calendar(name, open_time=None, close_time=None):
    """
    Retrieves an instance of an MarketCalendar whose name is given.

    :param name: The name of the MarketCalendar to be retrieved.
    :param open_time: Market open time override as datetime.time object. If None then default is used.
    :param close_time: Market close time override as datetime.time object. If None then default is used.
    :return: MarketCalendar of the desired calendar.
    """
    return MarketCalendar.factory(name, open_time=open_time, close_time=close_time) 
Example 30
Source File: holiday.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def get_calendar(name):
    """
    Return an instance of a calendar based on its name.

    Parameters
    ----------
    name : str
        Calendar name to return an instance of
    """
    return holiday_calendars[name]() 
Example 31
Source File: client.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def get_calendar_event_feed(self, uri=None,
                              desired_class=gdata.calendar.data.CalendarEventFeed,
               auth_token=None, **kwargs):
    """Obtains a feed of events for the desired calendar.

    Args:
      uri: The uri of the desired calendar entry.
           Defaults to https://www.google.com/calendar/feeds/default/private/full.
      desired_class: class descended from atom.core.XmlElement to which a
                     successful response should be converted. If there is no
                     converter function specified (desired_class=None) then the
                     desired_class will be used in calling the
                     atom.core.parse function. If neither
                     the desired_class nor the converter is specified, an
                     HTTP reponse object will be returned. Defaults to
                     gdata.calendar.data.CalendarEventFeed.
      auth_token: An object which sets the Authorization HTTP header in its
                  modify_request method. Recommended classes include
                  gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                  among others. Represents the current user. Defaults to None
                  and if None, this method will look for a value in the
                  auth_token member of SpreadsheetsClient.
    """
    uri = uri or self.GetCalendarEventFeedUri()
    return self.get_feed(uri, auth_token=auth_token,
                         desired_class=desired_class, **kwargs) 
Example 32
Source File: interface.py    From Rqalpha-myquant-learning with Apache License 2.0 5 votes vote down vote up
def get_trading_calendar(self):
        """
        获取交易日历

        :return: list[`pandas.Timestamp`]
        """
        raise NotImplementedError 
Example 33
Source File: calendar_registry.py    From pandas_market_calendars with MIT License 5 votes vote down vote up
def get_calendar_names():
    """All Market Calendar names and aliases that can be used in "factory"
    :return: list(str)
    """
    return MarketCalendar.calendar_names() 
Example 34
Source File: __init__.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def GetCalendarEventEntryClass():
  return CalendarEventEntry


# This class is not completely defined here, because of a circular reference
# in which CalendarEventEntryLink and CalendarEventEntry refer to one another. 
Example 35
Source File: calendar.py    From xclim with Apache License 2.0 5 votes vote down vote up
def get_calendar(arr: Union[xr.DataArray, xr.Dataset], dim: str = "time") -> str:
    """Return the calendar of the time coord of the DataArray

    Parameters
    ----------
    arr : Union[xr.DataArray, xr.Dataset]
      Array/dataset with a datetime coordinate. Values must either be of datetime64 dtype or have a dt.calendar attribute.
    dim : str
      Name of the coordinate to check.

    Raises
    ------
    ValueError
        If `arr` doesn't have a datetime64 or cftime dtype.

    Returns
    -------
    str
      The cftime calendar name or "default" when the data is using numpy's datetime type (numpy.datetime64.
    """
    if arr[dim].dtype == "O":  # Assume cftime, if it fails, not our fault
        non_na_item = arr[dim].where(arr[dim].notnull(), drop=True)[0].item()
        cal = non_na_item.calendar
    elif "datetime64" in arr[dim].dtype.name:
        cal = "default"
    else:
        raise ValueError(
            f"Cannot infer calendars from timeseries of type {arr[dim][0].dtype}"
        )
    return cal 
Example 36
Source File: oandapy.py    From pyfx with MIT License 5 votes vote down vote up
def get_eco_calendar(self, **params):
        """Returns up to 1 year of economic calendar info
        Docs: http://developer.oanda.com/rest-live/forex-labs/
        """
        endpoint = 'labs/v1/calendar'
        return self.request(endpoint, params=params) 
Example 37
Source File: replay.py    From pyvac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_calendar(caldav_url):
    """
    Get the calendar using credentials from `credentials.py`.
    """
    url = caldav_url
    client = caldav.DAVClient(url)
    princ = caldav.Principal(client, url)
    return princ.calendars()[0] 
Example 38
Source File: cons.py    From akshare with MIT License 5 votes vote down vote up
def get_calendar():
    """
    获取交易日历至 2019 年结束, 这里的交易日历需要按年更新
    :return: json
    """
    setting_file_name = "calendar.json"
    setting_file_path = get_json_path(setting_file_name, __file__)
    return json.load(open(setting_file_path, "r")) 
Example 39
Source File: calendar.py    From EInk-Calendar with MIT License 5 votes vote down vote up
def get_calendar_days() -> Tuple[List[int], Tuple[int, int]]:
    """
    Get calendar grid of dates as well as starting week index and weekday index
    """
    today = datetime.date.today()
    year = today.year
    month = today.month
    weekday_idx = (today.weekday() + 1) % 7

    # week start on Sunday
    calendar_lib = calendar.Calendar(firstweekday=6)
    weeks: List[List[datetime.date]] = calendar_lib.monthdatescalendar(
        year, month)
    week_idx: int = 0
    for week in weeks:
        if week[weekday_idx] == today:
            break
        week_idx += 1
    if week_idx >= 5:
        month += 1
        if month > 12:
            month = 1
            year += 1
        weeks = calendar_lib.monthdatescalendar(year, month)
        week_idx = 0
    if len(weeks) >= 5:
        weeks = weeks[:5]
    week_list: List[datetime.date] = sum(weeks, [])
    return list(map(lambda date: date.day, week_list)), (week_idx, weekday_idx) 
Example 40
Source File: trakt_api2.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def get_my_calendar(self, start_date=None, days=None, cached=True):
        url = '/calendars/my/shows'
        if start_date: url += '/%s' % (start_date)
        if days is not None: url += '/%s' % (days)
        params = {'extended': 'full,images', 'auth': True}
        return self.__call_trakt(url, params=params, auth=True, cache_limit=24, cached=cached) 
Example 41
Source File: trakt_api2.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def get_calendar(self, start_date=None, days=None, cached=True):
        url = '/calendars/all/shows'
        if start_date: url += '/%s' % (start_date)
        if days is not None: url += '/%s' % (days)
        params = {'extended': 'full,images', 'auth': False}
        return self.__call_trakt(url, params=params, auth=False, cache_limit=24, cached=cached) 
Example 42
Source File: data_collection.py    From EverydayWechat with MIT License 5 votes vote down vote up
def get_calendar_info(calendar=True, is_tomorrow=False, _date=''):
    """ 获取万年历 """
    if not calendar:
        return None
    if not is_tomorrow:
        date = datetime.now().strftime('%Y%m%d')
    else:
        date = (datetime.now() + timedelta(days=1)).strftime('%Y%m%d')
    return get_rtcalendar(date)

    # else:
    #     time_now = datetime.now()
    #     week = WEEK_DICT[time_now.strftime('%A')]
    #     date = time_now.strftime('%Y-%m-%d')
    #     return '{} {}'.format(date, week) 
Example 43
Source File: __init__.py    From gdata-python3 with Apache License 2.0 5 votes vote down vote up
def GetCalendarEventEntryClass():
    return CalendarEventEntry


# This class is not completely defined here, because of a circular reference
# in which CalendarEventEntryLink and CalendarEventEntry refer to one another. 
Example 44
Source File: client.py    From gdata-python3 with Apache License 2.0 5 votes vote down vote up
def get_calendar_event_feed(self, uri=None,
                                desired_class=gdata.calendar.data.CalendarEventFeed,
                                auth_token=None, **kwargs):
        """Obtains a feed of events for the desired calendar.

        Args:
          uri: The uri of the desired calendar entry.
               Defaults to https://www.google.com/calendar/feeds/default/private/full.
          desired_class: class descended from atom.core.XmlElement to which a
                         successful response should be converted. If there is no
                         converter function specified (desired_class=None) then the
                         desired_class will be used in calling the
                         atom.core.parse function. If neither
                         the desired_class nor the converter is specified, an
                         HTTP reponse object will be returned. Defaults to
                         gdata.calendar.data.CalendarEventFeed.
          auth_token: An object which sets the Authorization HTTP header in its
                      modify_request method. Recommended classes include
                      gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                      among others. Represents the current user. Defaults to None
                      and if None, this method will look for a value in the
                      auth_token member of SpreadsheetsClient.
        """
        uri = uri or self.GetCalendarEventFeedUri()
        return self.get_feed(uri, auth_token=auth_token,
                             desired_class=desired_class, **kwargs) 
Example 45
Source File: labos.py    From dcubabot with MIT License 5 votes vote down vote up
def get_calendar(name):
    if calendars[name][0] is None:
        retries = 100
    elif should_reload(name):
        retries = 3
    else:
        retries = 0

    # Si load_calendar falló fallbackeo
    return load_calendar(name, retries) or calendars[name]


# Repite el siguiente valor del generador, útil para ver si un generador está
# vacío sin romperlo. 
Example 46
Source File: validation.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_calendar(calendar_public_id, namespace, db_session):
    valid_public_id(calendar_public_id)
    try:
        return db_session.query(Calendar). \
            filter(Calendar.public_id == calendar_public_id,
                   Calendar.namespace_id == namespace.id).one()
    except NoResultFound:
        raise NotFoundError('Calendar {} not found'.format(calendar_public_id)) 
Example 47
Source File: ical.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def get_calendar(name):
	all_calendars = get_calendars()
	try:
		return [cal for cal in all_calendars if cal.title == name][0]
	except IndexError:
		raise NameError("Could not find calendar with name '{}'".format(name)) 
Example 48
Source File: calendar_helpers.py    From woid with Apache License 2.0 5 votes vote down vote up
def get_calendar(year, month):
    blank_week = [0, 0, 0, 0, 0, 0, 0]
    calendar.setfirstweekday(calendar.SUNDAY)
    c = calendar.monthcalendar(year, month)
    if len(c) == 4:
        c.append(blank_week)
    if len(c) == 5:
        c.append(blank_week)
    return c 
Example 49
Source File: ghdecoy.py    From ghdecoy with ISC License 5 votes vote down vote up
def get_calendar(user):
    """Retrieves the given user's contribution data from Github."""

    url = 'https://github.com/users/' + user + '/contributions'
    try:
        page = urllib2.urlopen(url)
    except (urllib2.HTTPError, urllib2.URLError) as err:
        print "There was a problem fetching data from {0}".format(url)
        print err
        return None
    return page.readlines() 
Example 50
Source File: calendarwidget.py    From ttkwidgets with GNU General Public License v3.0 5 votes vote down vote up
def get_calendar(locale, fwday):
    # instantiate proper calendar class
    if locale is None:
        return calendar.TextCalendar(fwday)
    else:
        return calendar.LocaleTextCalendar(fwday, locale) 
Example 51
Source File: main.py    From nikeAPI-Py with MIT License 5 votes vote down vote up
def getCalendar(session,proxy):
	#"https://api.nike.com/commerce/productfeed/products/snkrs/threads?country=FR&lastUpdatedAfter=2018-03-25-00-00&limit=50&locale=fr_FR&skip=0&withCards=true"
	today = datetime.datetime.now().strftime("%Y-%m-%d-00-00")
	calendar_url = "https://api.nike.com/commerce/productfeed/products/snkrs/threads?country=FR&lastUpdatedAfter=" + today + "&limit=50&locale=fr_FR&skip=0&withCards=true"
	a = session.get(calendar_url,verify=False)
	decoded_resp = json.loads(a.text,encoding="utf-8")
	# you can do whatever you want with this
	return decoded_resp; 
Example 52
Source File: rest.py    From alpaca-trade-api-python with Apache License 2.0 5 votes vote down vote up
def get_calendar(self, start: str = None, end: str = None) -> Calendars:
        """
        :param start: isoformat date string eg '2006-01-02T15:04:05Z' or
               '2006-01-02'
        :param end: isoformat date string
        """
        params = {}
        if start is not None:
            params['start'] = start
        if end is not None:
            params['end'] = end
        resp = self.get('/calendar', data=params)
        return [Calendar(o) for o in resp] 
Example 53
Source File: traktapi.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 5 votes vote down vote up
def get_calendar_episodes(self, startdate=0, days=1, limit=25):
        items = []

        if not self.tmdb or not self.authorize():
            return items

        mod_date = startdate - 1
        mod_days = days + 2  # Broaden date range in case utc conversion bumps into different day
        date = datetime.date.today() + datetime.timedelta(days=mod_date)
        response = self.get_calendar('shows', True, start_date=date.strftime('%Y-%m-%d'), days=mod_days)

        if not response:
            return items

        traktitems = reversed(response) if startdate < -1 else response  # Reverse items for date ranges in past

        count = 0
        for i in traktitems:
            if not utils.date_in_range(i.get('first_aired'), utc_convert=True, start_date=startdate, days=days):
                continue  # Don't add items that aren't in our timezone converted range
            if count >= limit:
                break  # Only add the limit
            episode = i.get('episode', {}).get('number')
            season = i.get('episode', {}).get('season')
            tmdb_id = i.get('show', {}).get('ids', {}).get('tmdb')
            item = ListItem(library=self.library, **self.tmdb.get_detailed_item(
                itemtype='tv', tmdb_id=tmdb_id, season=season, episode=episode))
            item.tmdb_id, item.season, item.episode = tmdb_id, season, episode
            item = self.get_calendar_properties(item, i)
            items.append(item)
            count += 1
        return items