• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pyrfc3339.parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyrfc3339.parse函数的典型用法代码示例。如果您正苦于以下问题:Python parse函数的具体用法?Python parse怎么用?Python parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: schedule_message

    def schedule_message(self, data, time_slot):
        now_obj = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
        min_time_to_start = datetime.timedelta(hours=time_slot*4-4)
        max_time_to_start = datetime.timedelta(hours=time_slot*4)

        if time_slot == 0:
            intro = '**Current Rotation (Ends in {} hours and {} minutes):**\n'
        else:
            intro = '**In {} hours and {} minutes:**\n'

        for data_set in data['schedule']:
            start = pyrfc3339.parse(data_set['datetime_begin'])
            end = pyrfc3339.parse(data_set['datetime_end'])
            time_to_start = start - now_obj
            time_to_end = end - now_obj
            # print(min_time_to_start.total_seconds(), time_to_start.total_seconds(), max_time_to_start.total_seconds())
            if min_time_to_start <= time_to_start <= max_time_to_start:
                reg_1 = data_set['stages']['regular'][0]['name']
                reg_2 = data_set['stages']['regular'][1]['name']
                rank_1 = data_set['stages']['gachi'][0]['name']
                rank_2 = data_set['stages']['gachi'][1]['name']
                mode = data_set['gachi_rule']
                if time_slot == 0:
                    time_left = time_to_end
                else:
                    time_left = time_to_start
                hours = int(time_left.total_seconds() / 3600)
                minutes = int(time_left.total_seconds()/60) % 60
                msg = intro + "Turf War is {} and {}\n{} is {} and {}"
                return msg.format(hours, minutes, reg_1, reg_2, mode, rank_1, rank_2)

        return "There is no data currently for this time slot."
开发者ID:Brickmastr,项目名称:BrickBot,代码行数:32,代码来源:schedule.py


示例2: current_calendar_events

def current_calendar_events(calId, time_window=1):

    http = httplib2.Http()
    service = build(serviceName='calendar', version='v3', http=http,
                    developerKey='AIzaSyA96dI1CPIUEuzgi3-_H8dQVyM34rak5vE')

    # get a list of all events +/- the specified number of days from now
    now = datetime.utcnow().replace(tzinfo=pytz.utc)
    diffTime = timedelta(days=time_window)
    queryStart = now - diffTime
    queryEnd = now + diffTime

    dayStartString = pyrfc3339.generate(queryStart)
    dayEndString = pyrfc3339.generate(queryEnd)

    events = service.events().list(calendarId=calId, singleEvents=True, timeMin=dayStartString, timeMax=dayEndString, orderBy='updated').execute()

    eventList = []
    for event in events['items']:
        endTime = pyrfc3339.parse(event['end']['dateTime'])
        startTime = pyrfc3339.parse(event['start']['dateTime'])
        
        if now > startTime and now < endTime:
            eventList.append(event)
        
    return eventList
开发者ID:Br3nda,项目名称:hackPump,代码行数:26,代码来源:calendar_events.py


示例3: _daterange_filter

def _daterange_filter(query, params, state):
    """
    handles filtering by start and end date
    paramters: startdate, enddate
    """
    startdate = params.get('startdate')
    if startdate is not None:
        try:
            del params['startdate']
            try:
                startdate = parse_date(startdate, '%Y-%m-%d')
            except ValueError:
                startdate = pyrfc3339.parse(startdate)
            query = query.filter(pub_date__gte=startdate)
        except ValueError:
            raise QueryError('Invalid start date "%s", must be YYYY-MM-DD or rfc3339' % startdate)
    
    enddate = params.get('enddate')
    if enddate is not None:
        try:
            del params['enddate']
            try:
                enddate = parse_date(enddate, '%Y-%m-%d')
            except ValueError: 
                enddate = pyrfc3339.parse(enddate)
            query = query.filter(pub_date__lte=enddate)
        except ValueError:
            raise QueryError('Invalid end date "%s", must be YYYY-MM-DD or rfc3339' % enddate)

    return query, params, state
开发者ID:UniversityDailyKansan,项目名称:openblock,代码行数:30,代码来源:itemquery.py


示例4: validate_expiration_time

    def validate_expiration_time(self, original_value, value_in_question, type_=None):
        """
        Validate the expiration time value passed to Update or Create Methods.

        Args:
            original_value: The original value that needs to be compared (e.g., SLICE creation date)
            value_in_question: The value that is doubted for correctness (e.g., Expiry time update date)

        Returns:
            a boolean value to indicate whether the expiration time valid or not
        """
        parsed_original_value = pyrfc3339.parse(original_value)
        parsed_value_in_question = pyrfc3339.parse(value_in_question)
        now = pytz.timezone("UTC").localize(datetime.datetime.utcnow())

        # Check if the object has already expired
        if now > parsed_original_value:
            raise GFedv2ArgumentError("Update is not possible because the object has already expired: "+str(now)+" > "+str(parsed_original_value))

        if type_:
            maximum_expansion_duration = self.STATIC['CONFIG'][type_]['max_%s_extension_time' %type_.lower()]
            configuration_delta = datetime.timedelta(days=maximum_expansion_duration)
            delta_time_days =  parsed_value_in_question - parsed_original_value
            return True if parsed_original_value <= parsed_value_in_question and delta_time_days < configuration_delta else False
        else:
            return parsed_original_value <= parsed_value_in_question
开发者ID:EICT,项目名称:C-BAS,代码行数:26,代码来源:delegatetools.py


示例5: execute

    def execute(self):

        if self.__mode == 'eventview':
            if self.__updateSec > 60:
              now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
              try:
                eventsResult = self.__service.events().list(
                calendarId=self.__calendarID, timeMin=now, maxResults=5, singleEvents=True,
                orderBy='startTime').execute()
              except HttpError, err:
                if err.resp.status in [403, 500, 503]:
                  time.sleep(5)
                else: 
                  if err.resp.get('content-type', '').startswith('application/json'):
                    reason = json.loads(err.content).reason
                    print reason
                  raise
              
              events = eventsResult.get('items', [])
              self.__lg19.load_text("Calendar", 1,True, center=True, color="yellow")
              
              i = 3;
              if not events:
                  self.__lg19.load_text("No upcoming events found.", 2)
              for event in events:
                  if event['start'].get('dateTime') == None:
                      start = datetime.datetime.strptime(event['start'].get('date'),"%Y-%m-%d")
                      end = datetime.datetime.strptime(event['start'].get('date'),"%Y-%m-%d")
                      now = datetime.datetime.today()
                      prefix = " "
                      if start <= now <= end:
                          prefix = "-"
                      self.__lg19.load_text(prefix + start.strftime("%d/%m") + " " +event['summary'], i)
                  else:
                      start = parse(event['start'].get('dateTime'), utc=True)
                      end = parse(event['end'].get('dateTime'), utc=True)
                      now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
                      inhour = now + datetime.timedelta(hours=1)
                      late = now + datetime.timedelta(hours=6)
                      color = "white"
                      if start >= late:
                          color = "DarkGray"
                      if start <= inhour <= end:
                          color = "gold"
                      if start <= now <= end:
                          color = "red"
                      start = start.astimezone(get_localzone())
                      self.__lg19.load_text(start.strftime("%d/%m %H:%M") + " " +event['summary'], i, color=color)
                  i += 1
              
              self.__lg19.set_text()
              self.__updateSec = 0
            self.__updateSec += 1
            time.sleep(1)
开发者ID:Tyres91,项目名称:Logitech-G19-Linux-Daemon,代码行数:54,代码来源:calendar.py


示例6: test_zero_offset

    def test_zero_offset(self):
        '''
        Both +00:00 and -00:00 are equivalent to the offset 'Z' (UTC).

        '''
        timestamp = '2009-01-01T10:02:03+00:00'
        dt = parse(timestamp)
        eq_(dt.tzinfo, pytz.utc)

        timestamp = '2009-01-01T10:02:03-00:00'
        dt = parse(timestamp)
        eq_(dt.tzinfo, pytz.utc)
开发者ID:Roger,项目名称:y,代码行数:12,代码来源:tests.py


示例7: cancelEvent

def cancelEvent(evt_id, user_list, mail_list):
  service = initService()
  event = service.events().get(calendarId=calId, eventId=evt_id).execute()

  if not event.has_key('description') or event['description'].strip() == '':
    return 'CANCEL_NULL'

  user_str = event['description']

  for x in user_list:
    if user_str.find(x) != -1:
      event['description'] = ''
      update_event = service.events().update(calendarId=calId, eventId=event['id'], body=event).execute()
      
      creator_email = event['creator']['email']
      creator = event['summary']
      
      mail_list.append(creator_email)

      dtstart = parse(event['start']['dateTime']).strftime('%Y-%m-%d %H:%M:%S')
      dtend = parse(event['end']['dateTime']).strftime('%Y-%m-%d %H:%M:%S')

      for x in mail_list:
        if x.strip() != '':
          mail.send_mail(sender=creator_email, 
                            to=x,
                            subject="Cancelation of Private Tutoring Reservation",
                            body="""
          Hi,

          Instructor: %(instructor)s
          Start Time: %(dtstart)s
          End Time: %(dtend)s
          Participants: %(partici)s

          This mail confirms you that your request of Private Tutoring
          has been canceled.

          Best,

          %(creator)s
          """ % {'instructor':creator, 
                'dtstart':dtstart,
                'dtend':dtend,
                'partici':user_str,
                'creator':creator})

      return 'CANCEL_OK'
  
  return 'CANCEL_INVALID'
开发者ID:alfredyuan,项目名称:privateTutoring,代码行数:50,代码来源:middleware.py


示例8: check_datetime

    def check_datetime(value):
        """
        Check if value is a valid RFC3339 string.

        See RFC3339 for more details: http://www.ietf.org/rfc/rfc3339.txt

        Args:
            value: item to check

        Raises:
            Exception: value is not of valid RFC3339 string

        """
        pyrfc3339.parse(value)
开发者ID:fp7-alien,项目名称:C-BAS,代码行数:14,代码来源:delegatetools.py


示例9: p_expression_tagged_element

def p_expression_tagged_element(p):
    """expression : TAG expression"""
    tag = p[1]
    element = p[2]

    if tag == 'inst':
        length = len(element)
        hyphens_count = element.count('-')

        if length == 10 and hyphens_count == 2:
            output = datetime.datetime.strptime(element, '%Y-%m-%d').date()
        elif length == 7 and hyphens_count == 1:
            output = datetime.datetime.strptime(element, '%Y-%m').date()
        elif length == 4 and hyphens_count == 0:
            output = datetime.datetime.strptime(element, '%Y').date()
        else:
            output = pyrfc3339.parse(element)
    elif tag == 'uuid':
        output = uuid.UUID(element)
    elif tag in _serializers:
        output = _serializers[tag](element)
    else:
        raise NotImplementedError(
            u"Don't know how to handle tag ImmutableDict({})".format(tag))

    p[0] = output
开发者ID:swaroopch,项目名称:edn_format,代码行数:26,代码来源:edn_parse.py


示例10: _parse_time

def _parse_time(input):
    """
    :param input: Either a number as milliseconds since Unix Epoch, or a string as a valid RFC3339 timestamp
    :return: milliseconds since Unix epoch, or None if input was invalid.
    """

    # bool is a subtype of int, and we don't want to try and compare it as a time.
    if isinstance(input, bool):
        log.warn("Got unexpected bool type when attempting to parse time")
        return None

    if isinstance(input, Number):
        return float(input)

    if isinstance(input, six.string_types):
        try:
            parsed_time = pyrfc3339.parse(input)
            timestamp = (parsed_time - epoch).total_seconds()
            return timestamp * 1000.0
        except Exception as e:
            log.warn("Couldn't parse timestamp:" + str(input) + " with message: " + str(e))
            return None

    log.warn("Got unexpected type: " + type(input) + " with value: " + str(input) + " when attempting to parse time")
    return None
开发者ID:launchdarkly,项目名称:python-client,代码行数:25,代码来源:operators.py


示例11: _notAfterBefore

def _notAfterBefore(cert_path, method):
    """Internal helper function for finding notbefore/notafter.

    :param str cert_path: path to a cert in PEM format
    :param function method: one of ``OpenSSL.crypto.X509.get_notBefore``
        or ``OpenSSL.crypto.X509.get_notAfter``

    :returns: the notBefore or notAfter value from the cert at cert_path
    :rtype: :class:`datetime.datetime`

    """
    with open(cert_path) as f:
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())
    timestamp = method(x509)
    reformatted_timestamp = [
        timestamp[0:4],
        "-",
        timestamp[4:6],
        "-",
        timestamp[6:8],
        "T",
        timestamp[8:10],
        ":",
        timestamp[10:12],
        ":",
        timestamp[12:],
    ]
    return pyrfc3339.parse("".join(reformatted_timestamp))
开发者ID:kotishe,项目名称:letsencrypt,代码行数:28,代码来源:crypto_util.py


示例12: fetchPredictions

    def fetchPredictions(self, stopTag):
        r = requests.get(
            self.baseURL
            + "/rtt/public/utility/file.aspx?contenttype=SQLXML&Name=RoutePositionET.xml&PlatformTag="
            + stopTag
        )
        r.raise_for_status()

        predictionsTree = etree.fromstring(r.content)

        predictionData = {
            "agency": self.agency,
            "tag": stopTag,
            "expires": parse(
                predictionsTree.xpath("/c:RoutePositionET/c:Content/@Expires", namespaces=NSMAP)[0], utc=True
            ),
            "predictions": [],
        }

        for trip in predictionsTree.xpath(
            "/c:RoutePositionET/c:Platform/c:Route/c:Destination/c:Trip", namespaces=NSMAP
        ):
            predictionData["predictions"].append(
                {
                    "minutes": int(trip.attrib["ETA"]),
                    "destination": trip.xpath("../@Name")[0],
                    "route": trip.xpath("../../@RouteNo")[0],
                }
            )

        predictionData["predictions"].sort(key=lambda x: x["minutes"])

        return predictionData
开发者ID:homoludens,项目名称:CapitalTransitInfo,代码行数:33,代码来源:connexionz.py


示例13: go_to_py_cookie

def go_to_py_cookie(go_cookie):
    '''Convert a Go-style JSON-unmarshaled cookie into a Python cookie'''
    expires = None
    if go_cookie.get('Expires') is not None:
        t = pyrfc3339.parse(go_cookie['Expires'])
        expires = t.timestamp()
    return cookiejar.Cookie(
        version=0,
        name=go_cookie['Name'],
        value=go_cookie['Value'],
        port=None,
        port_specified=False,
        # Unfortunately Python cookies don't record the original
        # host that the cookie came from, so we'll just use Domain
        # for that purpose, and record that the domain was specified,
        # even though it probably was not. This means that
        # we won't correctly record the CanonicalHost entry
        # when writing the cookie file after reading it.
        domain=go_cookie['Domain'],
        domain_specified=not go_cookie['HostOnly'],
        domain_initial_dot=False,
        path=go_cookie['Path'],
        path_specified=True,
        secure=go_cookie['Secure'],
        expires=expires,
        discard=False,
        comment=None,
        comment_url=None,
        rest=None,
        rfc2109=False,
    )
开发者ID:juju-solutions,项目名称:python-libjuju,代码行数:31,代码来源:gocookies.py


示例14: _notAfterBefore

def _notAfterBefore(cert_path, method):
    """Internal helper function for finding notbefore/notafter.

    :param str cert_path: path to a cert in PEM format
    :param function method: one of ``OpenSSL.crypto.X509.get_notBefore``
        or ``OpenSSL.crypto.X509.get_notAfter``

    :returns: the notBefore or notAfter value from the cert at cert_path
    :rtype: :class:`datetime.datetime`

    """
    # pylint: disable=redefined-outer-name
    with open(cert_path) as f:
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                               f.read())
    # pyopenssl always returns bytes
    timestamp = method(x509)
    reformatted_timestamp = [timestamp[0:4], b"-", timestamp[4:6], b"-",
                             timestamp[6:8], b"T", timestamp[8:10], b":",
                             timestamp[10:12], b":", timestamp[12:]]
    timestamp_str = b"".join(reformatted_timestamp)
    # pyrfc3339 uses "native" strings. That is, bytes on Python 2 and unicode
    # on Python 3
    if six.PY3:
        timestamp_str = timestamp_str.decode('ascii')
    return pyrfc3339.parse(timestamp_str)
开发者ID:pombredanne,项目名称:certbot,代码行数:26,代码来源:crypto_util.py


示例15: expiry_time

def expiry_time(ns, cavs):
    ''' Returns the minimum time of any time-before caveats found
    in the given list or None if no such caveats were found.

    The ns parameter is
    :param ns: used to determine the standard namespace prefix - if
    the standard namespace is not found, the empty prefix is assumed.
    :param cavs: a list of pymacaroons.Caveat
    :return: datetime.DateTime or None.
    '''
    prefix = ns.resolve(STD_NAMESPACE)
    time_before_cond = condition_with_prefix(
        prefix, COND_TIME_BEFORE)
    t = None
    for cav in cavs:
        if not cav.first_party():
            continue
        cav = cav.caveat_id_bytes.decode('utf-8')
        name, rest = parse_caveat(cav)
        if name != time_before_cond:
            continue
        try:
            et = pyrfc3339.parse(rest)
            if t is None or et < t:
                t = et
        except ValueError:
            continue
    return t
开发者ID:fabricematrat,项目名称:py-macaroon-bakery,代码行数:28,代码来源:time.py


示例16: test_parse_naive_utc

    def test_parse_naive_utc(self):
        '''
        Test parsing a UTC timestamp to a naive datetime.

        '''
        dt1 = parse('2009-01-01T10:01:02Z', produce_naive=True)
        eq_(dt1.tzinfo, None)
开发者ID:Roger,项目名称:y,代码行数:7,代码来源:tests.py


示例17: updateEvent

def updateEvent(evt_id, user_str, mail_list):
  service = initService()
  event = service.events().get(calendarId=calId, eventId=evt_id).execute()

  #return event['id']
  creator_email = event['creator']['email']
  creator = event['summary']

  if event.has_key('description') and event['description'].strip() != '':
    return 'RESERVED'

  event['description'] = user_str

  update_event = service.events().update(calendarId=calId, eventId=event['id'], body=event).execute()

  mail_list.append(creator_email)

  dtstart = parse(event['start']['dateTime']).strftime('%Y-%m-%d %H:%M:%S')
  dtend = parse(event['end']['dateTime']).strftime('%Y-%m-%d %H:%M:%S')

  for x in mail_list:
    if x.strip() != '':
      mail.send_mail(sender=creator_email, 
                        to=x,
                        subject="Confirmation of Private Tutoring Reservation",
                        body="""
      Hi,

      Instructor: %(instructor)s
      Start Time: %(dtstart)s
      End Time: %(dtend)s
      Participants: %(partici)s

      This mail confirms you that your request of Private Tutoring
      has been received by GSI. Once location is determined, GSI 
      will contact you with details.

      Best,

      %(creator)s
      """ % {'instructor':creator, 
            'dtstart':dtstart,
            'dtend':dtend,
            'partici':user_str,
            'creator':creator})

  return 'RESERVE_OK'
开发者ID:alfredyuan,项目名称:privateTutoring,代码行数:47,代码来源:middleware.py


示例18: test_parse_microseconds

    def test_parse_microseconds(self):
        '''
        Test parsing timestamps with microseconds.

        '''
        timestamp = '2009-01-01T10:02:03.25Z'
        dt = parse(timestamp)
        eq_(dt.microsecond, 250000)
开发者ID:Roger,项目名称:y,代码行数:8,代码来源:tests.py


示例19: test_deepcopy

    def test_deepcopy(self):
        '''
        Tests that deepcopy works and doesn't crash

        '''
        timestamp = '2009-01-01T10:02:03+02:00'
        dt = parse(timestamp)
        deepcopy(dt)
开发者ID:kurtraschke,项目名称:pyRFC3339,代码行数:8,代码来源:tests.py


示例20: get_execution_time

def get_execution_time(text):
    soup = BeautifulSoup(text)
    execution_time = soup.find("executiontime")
    if not execution_time:
        error = handle_error(text)
        raise ValueError(error)
    else:
        return parse(execution_time.text)
开发者ID:sigurdga,项目名称:samklang-payment,代码行数:8,代码来源:views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyro.clear_param_store函数代码示例发布时间:2022-05-27
下一篇:
Python pyrfc3339.generate函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap