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


Python humanfriendly.format_timespan方法代码示例

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


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

示例1: wait_until_connected

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def wait_until_connected(self):
        """
        Wait until connections are being accepted.

        :raises: :exc:`TimeoutError` when the SSH server isn't fast enough to
                 initialize.
        """
        timer = Timer()
        with Spinner(timer=timer) as spinner:
            while not self.is_connected:
                if timer.elapsed_time > self.wait_timeout:
                    raise TimeoutError(format(
                        "Failed to establish connection to %s within configured timeout of %s!",
                        self.endpoint, format_timespan(self.wait_timeout),
                    ))
                spinner.step(label="Waiting for %s to accept connections" % self.endpoint)
                spinner.sleep()
        logger.debug("Waited %s for %s to accept connections.", timer, self.endpoint) 
开发者ID:xolox,项目名称:python-executor,代码行数:20,代码来源:tcp.py

示例2: get_info

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def get_info(self, ctx: commands.Context, guild: discord.Guild):
        # This takes both context and guild to allow for showing public
        # guilds in the future
        created = guild.created_at.strftime('%b %-d %Y @ %I:%M %p')
        cdelta = humanfriendly.format_timespan(
            datetime.datetime.utcnow() - guild.created_at,
            max_units=2
        ) + ' ago'
        info = [
            f'**Created by {guild.owner or "Unknown#0000"} {cdelta}**',
            f'**Members:** {guild.member_count:,d}',
            f'**Region:** {region.get(str(guild.region), "❓ Deprecated Region")}'
        ]
        is_cached = len(guild.members) / guild.member_count
        if is_cached > 0.98 and guild.get_member(ctx.author):
            # is_cached should be 1.0 if cached but allow for discrepancies
            joinpos = sorted(
                guild.members,
                key=lambda m: m.joined_at or m.created_at
            ).index(ctx.author) + 1
            info.append(f'**Your Join Position:** {joinpos:,d}')
        return info 
开发者ID:FireDiscordBot,项目名称:bot,代码行数:24,代码来源:guild.py

示例3: __call__

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def __call__(self, name, log_func=None):
        """
        Example.
            timer = Timer(log)
            with timer("Some Routines"):
                routine1()
                routine2()
        """
        if log_func is None:
            log_func = self.log.info

        start = time.clock()
        yield
        end = time.clock()
        duration = end - start
        readable_duration = format_timespan(duration)
        log_func(f"{name} :: {readable_duration}") 
开发者ID:hyperconnect,项目名称:MMNet,代码行数:19,代码来源:utils.py

示例4: _can_run_next_block

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def _can_run_next_block(self) -> bool:
        if not in_standalone_mode:
            estimated_time = self.stats_helper.estimate_time_for_next_round(self.run_block_size,
                                                                            all=self.block_run_count < self.min_runs)
            to_bench_count = len(self.stats_helper.get_program_ids_to_bench())
            if -1 < self.end_time < round(time.time() + estimated_time):
                logging.warning("Ran too long ({}) and is therefore now aborted. "
                                "{} program blocks should've been benchmarked again."
                                .format(humanfriendly.format_timespan(time.time() + estimated_time - self.start_time),
                                        to_bench_count))
                return False
        if self.block_run_count >= self.maximum_of_max_runs() and self.block_run_count >= self.maximum_of_min_runs():
            #print("benchmarked too often, block run count ", self.block_run_count, self.block_run_count + self.run_block_size > self.min_runs)
            logging.warning("Benchmarked program blocks too often and aborted therefore now.")
            return False
        return True 
开发者ID:parttimenerd,项目名称:temci,代码行数:18,代码来源:run_processor.py

示例5: humanfriendly_age_from_datetime

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def humanfriendly_age_from_datetime(dt, detailed=False, max_unit=2):
    return humanfriendly.format_timespan(datetime.utcnow() - dt, detailed, max_unit) 
开发者ID:bentoml,项目名称:BentoML,代码行数:4,代码来源:utils.py

示例6: log_message

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def log_message(self, epoch: int = None) -> str:
        if epoch is None:
            epoch = self.get_epoch()

        message = ""
        for key, d in self.stats[epoch].items():
            _message = ""
            for key2, v in d.items():
                if v is not None:
                    if len(_message) != 0:
                        _message += ", "
                    if isinstance(v, float):
                        if abs(v) > 1.0e3:
                            _message += f"{key2}={v:.3e}"
                        elif abs(v) > 1.0e-3:
                            _message += f"{key2}={v:.3f}"
                        else:
                            _message += f"{key2}={v:.3e}"
                    elif isinstance(v, datetime.timedelta):
                        _v = humanfriendly.format_timespan(v)
                        _message += f"{key2}={_v}"
                    else:
                        _message += f"{key2}={v}"
            if len(_message) != 0:
                if len(message) == 0:
                    message += f"{epoch}epoch results: "
                else:
                    message += ", "
                message += f"[{key}] {_message}"
        return message 
开发者ID:espnet,项目名称:espnet,代码行数:32,代码来源:reporter.py

示例7: get_info

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def get_info(self, ctx: commands.Context, user: typing.Union[discord.User, discord.Member]):
        created = user.created_at.strftime('%b %-d %Y @ %I:%M %p')
        cdelta = humanfriendly.format_timespan(
            datetime.datetime.utcnow() - user.created_at,
            max_units=2
        ) + ' ago'
        info = [
            f'**Mention:** {user.mention}',
            f'**Created:** {created} ({cdelta})'
        ]
        if isinstance(user, discord.Member):
            joined = user.joined_at.strftime('%b %-d %Y @ %I:%M %p')
            jdelta = humanfriendly.format_timespan(
                datetime.datetime.utcnow() - user.joined_at,
                max_units=2
            ) + ' ago'
            if ctx.guild and ctx.guild.owner == user:
                info.append(f'**Created Guild:** {joined} ({jdelta})')
            else:
                info.append(f'**Joined:** {joined} ({jdelta})')
            is_cached = len(ctx.guild.members) / ctx.guild.member_count
            if is_cached > 0.98:  # is_cached should be 1.0 if cached but allow for discrepancies
                joinpos = sorted(
                    ctx.guild.members,
                    key=lambda m: m.joined_at or m.created_at
                ).index(user) + 1
                info.append(f'**Join Position:** {joinpos:,d}')
            if user.nick and user.nick != user.name:
                info.append(f'**Nickname:** {user.nick}')
        return info 
开发者ID:FireDiscordBot,项目名称:bot,代码行数:32,代码来源:user.py

示例8: remindme

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def remindme(self, ctx, *, reminder: str):
		if parseTime(reminder):
			days, hours, minutes, seconds = parseTime(reminder)
			reminder = parseTime(reminder, True)
			if not reminder.replace(' ', '') or not reminder:
				return await ctx.error('Invalid format. Please provide a reminder along with the time')
		else:
			return await ctx.error('Invalid format. Please use the format "DAYSd HOURSh MINUTESm SECONDSs" along with your reminder')
		if not days and not hours and not minutes and not seconds:
			return await ctx.error('Invalid format. Please provide a time')
		if not days and not hours and not minutes and seconds < 120:
			return await ctx.error('If you need a bot to remind you about something in less than two minutes you should *probably* be worried...')
		try:
			forwhen = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=days, seconds=seconds, minutes=minutes, hours=hours)
		except OverflowError:
			return await ctx.error(f'Somehow I don\'t think Discord is gonna be around for that long. Reminders are limited to 3 months anyways')
		limit = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=90)
		if forwhen > limit and not await self.bot.is_owner(ctx.author):
			return await ctx.error('Reminders currently cannot be set for more than 3 months (90 days)')
		if ctx.author.id not in self.reminders:
			try:
				await ctx.author.send('Hey, I\'m just checking to see if I can DM you as this is where I will send your reminder :)')
			except discord.Forbidden:
				return await ctx.error('I was unable to DM you.\nI send reminders in DMs so you must make sure "Allow direct messages from server members." is enabled in at least one mutual server')
		reminder = reminder.strip()
		con = await self.bot.db.acquire()
		async with con.transaction():
			query = 'INSERT INTO remind (\"uid\", \"forwhen\", \"reminder\") VALUES ($1, $2, $3);'
			await self.bot.db.execute(query, ctx.author.id, forwhen.timestamp(), reminder)
		await self.bot.db.release(con)
		await self.loadremind()
		return await ctx.success(f'Reminder set for {humanfriendly.format_timespan(datetime.timedelta(days=days, seconds=seconds, minutes=minutes, hours=hours))} from now') 
开发者ID:FireDiscordBot,项目名称:bot,代码行数:34,代码来源:utils.py

示例9: reminders

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def reminders(self, ctx):
		mine = sorted(self.reminders.get(ctx.author.id, []), key=lambda r: r['for'])
		if not mine:
			return await ctx.error('You have no reminders.')
		paginator = WrappedPaginator(prefix='', suffix='', max_size=1980)
		for i, r in enumerate(mine):
			forwhen = datetime.datetime.fromtimestamp(r['for'], datetime.timezone.utc).strftime('%b %-d %Y @ %I:%M %p')
			delta = humanfriendly.format_timespan(datetime.datetime.fromtimestamp(r['for'], datetime.timezone.utc) - datetime.datetime.now(datetime.timezone.utc), max_units=2)
			paginator.add_line(f'[{i + 1}] {r["reminder"]} - {forwhen} ({delta})')
		interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author)
		return await interface.send_to(ctx) 
开发者ID:FireDiscordBot,项目名称:bot,代码行数:13,代码来源:utils.py

示例10: delremind

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def delremind(self, ctx, i: int = None):
		mine = sorted(self.reminders.get(ctx.author.id, []), key=lambda r: r['for'])
		if not mine:
			return await ctx.error('You have no reminders.')
		if not i:
			return await ctx.error(f'You must specify the reminder to delete. Use the [number] from `{ctx.prefix}reminders` to select a reminder')
		i -= 1  # Arrays start at 0
		if i >= len(mine):
			return await ctx.error(f'You don\'t have that many reminders. Use the [number] from `{ctx.prefix}reminders` to select a reminder')
		r = mine[i]
		forwhen = datetime.datetime.fromtimestamp(r['for'], datetime.timezone.utc).strftime('%b %-d %Y @ %I:%M %p')
		delta = humanfriendly.format_timespan(datetime.datetime.fromtimestamp(r['for'], datetime.timezone.utc) - datetime.datetime.now(datetime.timezone.utc), max_units=2)
		await self.deleteremind(ctx.author.id, r['for'])
		return await ctx.success(f'Your reminder, "{r["reminder"]}" for {forwhen} ({delta} from now), has been deleted!') 
开发者ID:FireDiscordBot,项目名称:bot,代码行数:16,代码来源:utils.py

示例11: format_timespan

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def format_timespan(duration):
    if duration < 10:
        readable_duration = "{:.1f} (ms)".format(duration * 1000)
    else:
        readable_duration = hf.format_timespan(duration)
    return readable_duration 
开发者ID:hyperconnect,项目名称:MMNet,代码行数:8,代码来源:utils.py

示例12: timer

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def timer(name):
    st = time.time()
    yield
    print("<Timer> {} : {}".format(name, format_timespan(time.time() - st))) 
开发者ID:hyperconnect,项目名称:MMNet,代码行数:6,代码来源:utils.py

示例13: wait

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def wait(message, stop_checker_closure):
    assert callable(stop_checker_closure)
    st = time.time()
    while True:
        try:
            time_pass = hf.format_timespan(int(time.time() - st))
            sys.stdout.write(colored((
                f"{message}. Do you wanna wait? If not, then ctrl+c! :: waiting time: {time_pass}\r"
            ), "yellow", attrs=["bold"]))
            sys.stdout.flush()
            time.sleep(1)
            if stop_checker_closure():
                break
        except KeyboardInterrupt:
            break 
开发者ID:hyperconnect,项目名称:MMNet,代码行数:17,代码来源:utils.py

示例14: format_timespan

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def format_timespan(seconds, short=False, pad=False):
    """Wrapper for human friendly, shorten words."""
    h = humanfriendly.format_timespan(int(seconds))
    if short:
        h = h.replace(' weeks', 'w')
        h = h.replace(' week', 'w')
        h = h.replace(' days', 'd')
        h = h.replace(' day', 'd')
        h = h.replace(' hours', 'h')
        h = h.replace(' hour', 'h')
        h = h.replace(' minutes', 'm')
        h = h.replace(' minute', 'm')
        h = h.replace(' seconds', 's')
        h = h.replace(' second', 's')
        h = h.replace(',', '')
        h = h.replace(' and', '')
        h = h.replace('  ', ' ')
    else:
        h = h.replace('week', 'wk')
        h = h.replace('hour', 'hr')
        h = h.replace('minute', 'min')
        h = h.replace('second', 'sec')
    if pad:
        h = ' ' + h
        h = re.sub('(\D)(\d)(\D)', r'\g<1>0\2\3', h)
        h = h.strip()
    return h 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:29,代码来源:clans.py

示例15: futureme

# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import format_timespan [as 别名]
def futureme(self, ctx):
        """Return list of future events set by remindme."""
        author = ctx.message.author
        author_reminders = []
        for r in self.reminders:
            if r["ID"] == author.id:
                if r["FUTURE"] >= int(time.time()):
                    author_reminders.append(r)
        if len(author_reminders) == 0:
            await self.bot.say("You have no future evnets.")
            return

        author_reminders = sorted(author_reminders, key=lambda x: x["FUTURE"])
        out = ["Here are your list of reminders:"]
        for i, r in enumerate(author_reminders, 1):
            out.append("**{}. {}**\n{}".format(
                i,
                humanfriendly.format_timespan(r["FUTURE"] - time.time()),
                r["TEXT"]
            ))
        try:
            await self.bot.send_message(
                author,
                "\n".join(out))
            await self.bot.say("Check your DM for all your future events.")
        except (discord.errors.Forbidden, discord.errors.NotFound):
            await self.bot.say("\n".join(out))
        except discord.errors.HTTPException:
            pass 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:31,代码来源:remindme_ext.py


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