當前位置: 首頁>>代碼示例>>Python>>正文


Python time.html方法代碼示例

本文整理匯總了Python中time.html方法的典型用法代碼示例。如果您正苦於以下問題:Python time.html方法的具體用法?Python time.html怎麽用?Python time.html使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在time的用法示例。


在下文中一共展示了time.html方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: classify

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def classify(self, contents):
        """BosonNLP `新聞分類接口 <http://docs.bosonnlp.com/classify.html>`_ 封裝。

        :param contents: 需要做分類的新聞文本或者文本序列。
        :type contents: string or sequence of string

        :returns: 接口返回的結果列表。

        :raises: :py:exc:`~bosonnlp.HTTPError` 如果 API 請求發生錯誤。

        調用示例:

        >>> import os
        >>> nlp = BosonNLP(os.environ['BOSON_API_TOKEN'])
        >>> nlp.classify('俄否決安理會譴責敘軍戰機空襲阿勒頗平民')
        [5]
        >>> nlp.classify(['俄否決安理會譴責敘軍戰機空襲阿勒頗平民',
        ...               '鄧紫棋談男友林宥嘉:我覺得我比他唱得好',
        ...               'Facebook收購印度初創公司'])
        [5, 4, 8]
        """
        api_endpoint = '/classify/analysis'
        r = self._api_request('POST', api_endpoint, data=contents)
        return r.json() 
開發者ID:bosondata,項目名稱:bosonnlp.py,代碼行數:26,代碼來源:client.py

示例2: suggest

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def suggest(self, word, top_k=None):
        """BosonNLP `語義聯想接口 <http://docs.bosonnlp.com/suggest.html>`_ 封裝。

        :param string word: 需要做語義聯想的詞。

        :param int top_k: 默認為 10,最大值可設定為 100。返回的結果條數。

        :returns: 接口返回的結果列表。

        :raises: :py:exc:`~bosonnlp.HTTPError` 如果 API 請求發生錯誤。

        調用示例:

        >>> import os
        >>> nlp = BosonNLP(os.environ['BOSON_API_TOKEN'])
        >>> nlp.suggest('北京', top_k=2)
        [[1.0, '北京/ns'], [0.7493540460397998, '上海/ns']]
        """
        api_endpoint = '/suggest/analysis'
        params = {}
        if top_k is not None:
            params['top_k'] = top_k
        r = self._api_request('POST', api_endpoint, params=params, data=word)
        return r.json() 
開發者ID:bosondata,項目名稱:bosonnlp.py,代碼行數:26,代碼來源:client.py

示例3: strptime

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def strptime(cls, string, format):
        """
        Constructs a :class:`mw.Timestamp` from an explicitly formatted string.
        See `<https://docs.python.org/3/library/time.html#time.strftime>`_ for a
        discussion of formats descriptors.

        :Parameters:
            string : str
                A formatted timestamp
            format : str
                The format description

        :Returns:
            :class:`mw.Timestamp`
        """
        return cls.from_time_struct(time.strptime(string, format)) 
開發者ID:mediawiki-utilities,項目名稱:python-mediawiki-utilities,代碼行數:18,代碼來源:timestamp.py

示例4: DatetimeToUTCMicros

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def DatetimeToUTCMicros(date):
  """Converts a datetime object to microseconds since the epoch in UTC.

  Args:
    date: A datetime to convert.
  Returns:
    The number of microseconds since the epoch, in UTC, represented by the input
    datetime.
  """
  # Using this guide: http://wiki.python.org/moin/WorkingWithTime
  # And this conversion guide: http://docs.python.org/library/time.html

  # Turn the date parameter into a tuple (struct_time) that can then be
  # manipulated into a long value of seconds.  During the conversion from
  # struct_time to long, the source date in UTC, and so it follows that the
  # correct transformation is calendar.timegm()
  micros = calendar.timegm(date.utctimetuple()) * _MICROSECONDS_PER_SECOND
  return micros + date.microsecond 
開發者ID:google,項目名稱:google-apputils,代碼行數:20,代碼來源:datelib.py

示例5: curtime

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def curtime(timeStr="%d.%m.%Y %H:%M:%S", timestamp=""):
	"""
	Returns formated date and/or time
	see: https://docs.python.org/2/library/time.html#time.strftime

	@type    format: string
	@param   format: Python time Format-String
	@type    timestamp: floating point number
	@param   timestamp: time in seconds since the epoch

	@return:    Formated Time and/or Date
	@exception: Exception if Error in format
	"""
	try:
		if timestamp == "":
			return time.strftime(timeStr)
		else:
			return time.strftime(timeStr, time.localtime(timestamp))
	except:
		logging.warning("error in time-format-string")
		logging.debug("error in time-format-string", exc_info=True) 
開發者ID:Schrolli91,項目名稱:BOSWatch,代碼行數:23,代碼來源:timeHandler.py

示例6: AddShortTaskAbsolute

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def AddShortTaskAbsolute(self, startTime, func, *args, **kwargs):
        """
        This does the same as :meth:`AddShortTask`, but the `startTime` parameter
        specifies an absolute time expressed in floating point seconds since
        the epoch. Take a look at the documentation of `Python's time module`_,
        for more information about this time format. Again a little example::

            import time
            startTime = time.mktime((2007, 8, 15, 16, 53, 0, 0, 0, -1))
            eg.scheduler.AddShortTaskAbsolute(startTime, eg.TriggerEvent, "MyEvent")

        This will trigger the event "Main.MyEvent" at 16:53:00 on 15 August
        2007. If you run this code after this point of time, the
        :func:`eg.TriggerEvent` will be called immediately.

        .. _Python's time module: http://docs.python.org/lib/module-time.html
        """
        try:
            self.lock.acquire()
            task = (startTime, func, args, kwargs)
            heappush(self.heap, task)
            self.event.set()
        finally:
            self.lock.release()
        return task 
開發者ID:EventGhost,項目名稱:EventGhost,代碼行數:27,代碼來源:Scheduler.py

示例7: get_dhl_formatted_shipment_time

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def get_dhl_formatted_shipment_time(self):
        """
        Formats the shipment date and time in the DHL time format, including the UTC offset
        :return: formatted date time stamp
        """
        self.ship_datetime = self.ship_datetime or datetime.now()
        if not self.utc_offset:
            # time lib https://docs.python.org/3/library/time.html#time.strftime
            self.utc_offset = time.strftime('%z')  # just take the utc offset from the time lib
            self.utc_offset = self.utc_offset[:-2] + ':' + self.utc_offset[-2:]  # insert : in +0100 to get +01:00

        self.ship_datetime += timedelta(minutes=5)
        formatted_time = self.ship_datetime.strftime(self.dhl_datetime_format)
        return formatted_time + self.utc_offset 
開發者ID:benqo,項目名稱:python-dhl,代碼行數:16,代碼來源:shipment.py

示例8: safe_sleep

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def safe_sleep(seconds):
  """Ensure that the thread sleeps at a minimum the requested seconds.

  Until Python 3.5, there was no guarantee that time.sleep() would actually sleep the requested
  time. See https://docs.python.org/3/library/time.html#time.sleep."""
  if sys.version_info[0:2] >= (3, 5):
    time.sleep(seconds)
  else:
    start_time = current_time = time.time()
    while current_time - start_time < seconds:
      remaining_time = seconds - (current_time - start_time)
      time.sleep(remaining_time)
      current_time = time.time() 
開發者ID:pantsbuild,項目名稱:pex,代碼行數:15,代碼來源:common.py

示例9: finalize

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def finalize(self, source=None):
    """Rename `work_dir` to `target_dir` using `os.rename()`.

    :param str source: An optional source offset into the `work_dir`` to use for the atomic
                       update of `target_dir`. By default the whole `work_dir` is used.

    If a race is lost and `target_dir` already exists, the `target_dir` dir is left unchanged and
    the `work_dir` directory will simply be removed.
    """
    if self.is_finalized:
      return

    source = os.path.join(self._work_dir, source) if source else self._work_dir
    try:
      # Perform an atomic rename.
      #
      # Per the docs: https://docs.python.org/2.7/library/os.html#os.rename
      #
      #   The operation may fail on some Unix flavors if src and dst are on different filesystems.
      #   If successful, the renaming will be an atomic operation (this is a POSIX requirement).
      #
      # We have satisfied the single filesystem constraint by arranging the `work_dir` to be a
      # sibling of the `target_dir`.
      os.rename(source, self._target_dir)
    except OSError as e:
      if e.errno not in (errno.EEXIST, errno.ENOTEMPTY):
        raise e
    finally:
      self.cleanup() 
開發者ID:pantsbuild,項目名稱:pex,代碼行數:31,代碼來源:common.py

示例10: consume

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def consume(self, subscription_name, callback, scheduler):
        """Begin listening to topic from the SubscriberClient.

        :param subscription_name: str Subscription name
        :param callback: Function which act on a topic message
        :param scheduler: `Thread pool-based scheduler.<https://googleapis.dev/python/pubsub/latest/subscriber/api/scheduler.html?highlight=threadscheduler#google.cloud.pubsub_v1.subscriber.scheduler.ThreadScheduler>`_  # noqa
        :return: `Future <https://googleapis.github.io/google-cloud-python/latest/pubsub/subscriber/api/futures.html>`_  # noqa
        """
        subscription_path = self._client.subscription_path(
            self._gc_project_id, subscription_name
        )
        return self._client.subscribe(
            subscription_path, callback=callback, scheduler=scheduler
        ) 
開發者ID:mercadona,項目名稱:rele,代碼行數:16,代碼來源:client.py

示例11: sentiment

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def sentiment(self, contents, model='general'):
        """BosonNLP `情感分析接口 <http://docs.bosonnlp.com/sentiment.html>`_ 封裝。

        :param contents: 需要做情感分析的文本或者文本序列。
        :type contents: string or sequence of string

        :param model: 使用不同語料訓練的模型,默認使用通用模型。
        :type model: string

        :returns: 接口返回的結果列表。

        :raises: :py:exc:`~bosonnlp.HTTPError` 如果 API 請求發生錯誤。

        調用示例:

        >>> import os
        >>> nlp = BosonNLP(os.environ['BOSON_API_TOKEN'])
        >>> nlp.sentiment('這家味道還不錯', model='food')
        [[0.9991737012037423, 0.0008262987962577828]]
        >>> nlp.sentiment(['這家味道還不錯', '菜品太少了而且還不新鮮'], model='food')
        [[0.9991737012037423, 0.0008262987962577828],
         [9.940036427291687e-08, 0.9999999005996357]]
        """
        api_endpoint = '/sentiment/analysis?' + model
        r = self._api_request('POST', api_endpoint, data=contents)
        return r.json() 
開發者ID:bosondata,項目名稱:bosonnlp.py,代碼行數:28,代碼來源:client.py

示例12: convert_time

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def convert_time(self, content, basetime=None):
        """BosonNLP `時間描述轉換接口 <http://docs.bosonnlp.com/time.html>`_ 封裝

        :param content: 中文時間描述字符串
        :type content: string

        :param basetime: 時間描述的基準時間,傳入一個時間戳或datetime
        :type basetime: int or datetime.datetime

        :raises: :py:exc:`~bosonnlp.HTTPError` 如果 API 請求發生錯誤。

        :returns: 接口返回的結果

        調用示例:

        >>> import os
        >>> nlp = BosonNLP(os.environ['BOSON_API_TOKEN'])
        >>> _json_dumps(nlp.convert_time("2013年二月二十八日下午四點三十分二十九秒"))
        '{"timestamp": "2013-02-28 16:30:29", "type": "timestamp"}'
        >>> import datetime
        >>> _json_dumps(nlp.convert_time("今天晚上8點到明天下午3點", datetime.datetime(2015, 9, 1)))
        '{"timespan": ["2015-09-02 20:00:00", "2015-09-03 15:00:00"], "type": "timespan_0"}'

        """
        api_endpoint = '/time/analysis'
        params = {'pattern': content}
        if basetime:
            if isinstance(basetime, datetime.datetime):
                basetime = int(time.mktime(basetime.timetuple()))
            params['basetime'] = basetime
        r = self._api_request('POST', api_endpoint, params=params)
        return r.json() 
開發者ID:bosondata,項目名稱:bosonnlp.py,代碼行數:34,代碼來源:client.py

示例13: extract_keywords

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def extract_keywords(self, text, top_k=None, segmented=False):
        """BosonNLP `關鍵詞提取接口 <http://docs.bosonnlp.com/keywords.html>`_ 封裝。

        :param string text: 需要做關鍵詞提取的文本。

        :param int top_k: 默認為 100,返回的結果條數。

        :param bool segmented: 默認為 :py:class:`False`,`text` 是否已進行了分詞,如果為
            :py:class:`True`,則不會再對內容進行分詞處理。

        :returns: 接口返回的結果列表。

        :raises: :py:exc:`~bosonnlp.HTTPError` 如果 API 請求發生錯誤。

        調用示例:

        >>> import os
        >>> nlp = BosonNLP(os.environ['BOSON_API_TOKEN'])
        >>> nlp.extract_keywords('病毒式媒體網站:讓新聞迅速蔓延', top_k=2)
        [[0.8391345017584958, '病毒式'], [0.3802418301341705, '蔓延']]
        """
        api_endpoint = '/keywords/analysis'
        params = {}
        if segmented:
            params['segmented'] = 1
        if top_k is not None:
            params['top_k'] = top_k
        r = self._api_request('POST', api_endpoint, params=params, data=text)
        return r.json() 
開發者ID:bosondata,項目名稱:bosonnlp.py,代碼行數:31,代碼來源:client.py

示例14: sign

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def sign(username, private_key, generate_nonce=None, iat=None, algorithm=DEFAULT_ALGORITHM):
    """
    Create a signed JWT using the given username and RSA private key.

    :param username: Username (string) to authenticate as on the remote system.
    :param private_key: Private key to use to sign the JWT claim.
    :param generate_nonce: Optional. Callable to use to generate a new nonce. Defaults to
        `random.random <https://docs.python.org/3/library/random.html#random.random>`_.
    :param iat: Optional. Timestamp to include in the JWT claim. Defaults to
        `time.time <https://docs.python.org/3/library/time.html#time.time>`_.
    :param algorithm: Optional. Algorithm to use to sign the JWT claim. Default to ``RS512``.
        See `pyjwt.readthedocs.io <https://pyjwt.readthedocs.io/en/latest/algorithms.html>`_ for other possible algorithms.
    :return: JWT claim as a string.
    """
    iat = iat if iat else time.time()
    if not generate_nonce:
        generate_nonce = lambda username, iat: random.random()  # NOQA

    token_data = {
        'username': username,
        'time': iat,
        'nonce': generate_nonce(username, iat),
    }

    token = jwt.encode(token_data, private_key, algorithm=algorithm)
    return token 
開發者ID:crgwbr,項目名稱:asymmetric-jwt-auth,代碼行數:28,代碼來源:token.py

示例15: strftime

# 需要導入模塊: import time [as 別名]
# 或者: from time import html [as 別名]
def strftime(self, format):
        """
        Constructs a formatted string.
        See `<https://docs.python.org/3/library/time.html#time.strftime>`_ for a
        discussion of formats descriptors.

        :Parameters:
            format : str
                The format description

        :Returns:
            A formatted string
        """
        return time.strftime(format, self.__time) 
開發者ID:mediawiki-utilities,項目名稱:python-mediawiki-utilities,代碼行數:16,代碼來源:timestamp.py


注:本文中的time.html方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。