本文整理汇总了Python中humanize.naturaldelta方法的典型用法代码示例。如果您正苦于以下问题:Python humanize.naturaldelta方法的具体用法?Python humanize.naturaldelta怎么用?Python humanize.naturaldelta使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类humanize
的用法示例。
在下文中一共展示了humanize.naturaldelta方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: summarise_usage
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def summarise_usage():
wall_time = humanize.naturaldelta(time.time() - __before)
user_time = humanize.naturaldelta(os.times().user)
sys_time = os.times().system
if resource is None:
# Don't report max memory on Windows. We could do this using the psutil lib, via
# psutil.Process(os.getpid()).get_ext_memory_info().peak_wset if demand exists
maxmem_str = ""
else:
max_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
if sys.platform != "darwin":
max_mem *= 1024 # Linux and other OSs (e.g. freeBSD) report maxrss in kb
maxmem_str = "; max memory={}".format(
humanize.naturalsize(max_mem, binary=True)
)
logger.info("wall time = {}".format(wall_time))
logger.info("rusage: user={}; sys={:.2f}s".format(user_time, sys_time) + maxmem_str)
示例2: get_execution_stats
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def get_execution_stats(cls, fn, input_df, fn_args, fn_kwargs, calculate_memory):
start = time()
output_df = get_pandas_func(cls, fn)(input_df, *fn_args, **fn_kwargs)
exec_time = time() - start
exec_time_pretty = humanize.naturaldelta(exec_time)
if exec_time_pretty == "a moment":
exec_time_pretty = f"{round(exec_time,6)} seconds"
step_number = calc_step_number(fn.__name__, input_df)
input_memory_size = (
StepStats.calc_df_series_memory(input_df) if calculate_memory else None
)
output_memory_size = (
StepStats.calc_df_series_memory(output_df) if calculate_memory else None
)
ExecutionStats = namedtuple(
"ExecutionStats", "exec_time step_number input_memory_size output_memory_size",
)
execution_stats = ExecutionStats(
exec_time_pretty, step_number, input_memory_size, output_memory_size
)
return output_df, execution_stats
示例3: tempban
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def tempban(self, event, duration, user, reason=None):
member = event.guild.get_member(user)
if member:
self.can_act_on(event, member.id)
expires_dt = parse_duration(duration)
Infraction.tempban(self, event, member, reason, expires_dt)
self.queue_infractions()
self.confirm_action(event, maybe_string(
reason,
u':ok_hand: temp-banned {u} for {t} (`{o}`)',
u':ok_hand: temp-banned {u} for {t}',
u=member.user,
t=humanize.naturaldelta(expires_dt - datetime.utcnow()),
))
else:
raise CommandFail('invalid user')
示例4: cmd_remind
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def cmd_remind(self, event, duration, content):
if Reminder.count_for_user(event.author.id) > 30:
return event.msg.reply(':warning: you an only have 15 reminders going at once!')
remind_at = parse_duration(duration)
if remind_at > (datetime.utcnow() + timedelta(seconds=5 * YEAR_IN_SEC)):
return event.msg.reply(':warning: thats too far in the future, I\'ll forget!')
r = Reminder.create(
message_id=event.msg.id,
remind_at=remind_at,
content=content
)
self.reminder_task.set_next_schedule(r.remind_at)
event.msg.reply(':ok_hand: I\'ll remind you at {} ({})'.format(
r.remind_at.isoformat(),
humanize.naturaldelta(r.remind_at - datetime.utcnow()),
))
示例5: summarise_usage
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def summarise_usage():
# Don't report usage on Windows as the resource module is not available.
# We could do this using the psutil external library, if demand exists.
if _resource_module_available:
rusage = resource.getrusage(resource.RUSAGE_SELF)
user_time = humanize.naturaldelta(rusage.ru_utime)
sys_time = rusage.ru_stime
max_mem = rusage.ru_maxrss
if sys.platform != 'darwin':
max_mem *= 1024 # Linux and other OSs (e.g. freeBSD) report maxrss in kb
max_mem_str = humanize.naturalsize(max_mem, binary=True)
logger.info("rusage: user={}; sys={:.2f}s; max_rss={}".format(
user_time, sys_time, max_mem_str))
示例6: natural_last_modified
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def natural_last_modified(self):
last_modified = parsedate_to_datetime(self.last_modified)
now = datetime.now(timezone.utc)
tense = "from now" if last_modified > now else "ago"
return "{0} {1}".format(humanize.naturaldelta(now - last_modified), tense)
示例7: relative_datetime
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def relative_datetime(self):
"""Return human-readable relative time string."""
now = datetime.now(timezone.utc)
tense = "from now" if self.created_at > now else "ago"
return "{0} {1}".format(humanize.naturaldelta(now - self.created_at), tense)
示例8: command_about
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def command_about(self, event):
embed = MessageEmbed()
embed.set_author(name='Rowboat', icon_url=self.client.state.me.avatar_url, url='https://rowboat.party/')
embed.description = BOT_INFO
embed.add_field(name='Servers', value=str(Guild.select().count()), inline=True)
embed.add_field(name='Uptime', value=humanize.naturaldelta(datetime.utcnow() - self.startup), inline=True)
event.msg.reply(embed=embed)
示例9: command_uptime
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def command_uptime(self, event):
event.msg.reply('Rowboat was started {}'.format(
humanize.naturaldelta(datetime.utcnow() - self.startup)
))
示例10: infraction_info
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def infraction_info(self, event, infraction):
try:
user = User.alias()
actor = User.alias()
infraction = Infraction.select(Infraction, user, actor).join(
user,
on=((Infraction.user_id == user.user_id).alias('user'))
).switch(Infraction).join(
actor,
on=((Infraction.actor_id == actor.user_id).alias('actor'))
).where(
(Infraction.id == infraction) &
(Infraction.guild_id == event.guild.id)
).get()
except Infraction.DoesNotExist:
raise CommandFail('cannot find an infraction with ID `{}`'.format(infraction))
type_ = {i.index: i for i in Infraction.Types.attrs}[infraction.type_]
embed = MessageEmbed()
if type_ in (Infraction.Types.MUTE, Infraction.Types.TEMPMUTE, Infraction.Types.TEMPROLE):
embed.color = 0xfdfd96
elif type_ in (Infraction.Types.KICK, Infraction.Types.SOFTBAN):
embed.color = 0xffb347
else:
embed.color = 0xff6961
embed.title = str(type_).title()
embed.set_thumbnail(url=infraction.user.get_avatar_url())
embed.add_field(name='User', value=unicode(infraction.user), inline=True)
embed.add_field(name='Moderator', value=unicode(infraction.actor), inline=True)
embed.add_field(name='Active', value='yes' if infraction.active else 'no', inline=True)
if infraction.active and infraction.expires_at:
embed.add_field(name='Expires', value=humanize.naturaldelta(infraction.expires_at - datetime.utcnow()))
embed.add_field(name='Reason', value=infraction.reason or '_No Reason Given', inline=False)
embed.timestamp = infraction.created_at.isoformat()
event.msg.reply('', embed=embed)
示例11: seen
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def seen(self, event, user):
try:
msg = Message.select(Message.timestamp).where(
Message.author_id == user.id
).order_by(Message.timestamp.desc()).limit(1).get()
except Message.DoesNotExist:
return event.msg.reply(u"I've never seen {}".format(user))
event.msg.reply(u'I last saw {} {} ago (at {})'.format(
user,
humanize.naturaldelta(datetime.utcnow() - msg.timestamp),
msg.timestamp
))
示例12: LowPrecisionDuration
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def LowPrecisionDuration(duration: Union[datetime.timedelta, int, float]):
"""Given a timedelta or a number of seconds, return a low precision, natural
representation of the amount of time elapsed.
This is similar to Duration(), but with a lower precision in the generated
string, e.g. "a moment" rather than "530 ms".
Args:
duration: The duration to convert to a natural string.
Returns:
A natural representation of the duration.
"""
return humanize_lib.naturaldelta(duration)
示例13: _print_router_info
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def _print_router_info(router, agent=None):
loc = await router.get_location()
print(u" name: {}".format(router.name))
print(u" hex id: {}".format(router.id_hex))
print(u"id hash (base64): {}".format(hashFromHexId(router.id_hex)))
print(u" location: {}".format("unknown" if loc.countrycode is None else loc.countrycode))
print(u" address: {}:{} (DirPort={})".format(router.ip, router.or_port, router.dir_port))
print(u" flags: {}".format(" ".join(router.flags)))
diff = datetime.datetime.utcnow() - router.modified
print(u" last published: {} ago ({})".format(humanize.naturaldelta(diff), router.modified))
if agent:
print(util.colors.italic("Extended information from" + util.colors.green(" onionoo.torproject.org") + ":"))
details = await router.get_onionoo_details(agent)
details.setdefault('dir_address', '<none>')
details.setdefault('city_name', 'unknown')
details.setdefault('region_name', 'unknown')
details.setdefault('country_name', 'unknown')
details['or_addresses'] = ', '.join(details.get('or_addresses', []))
details['verified_host_names_formatted'] = ', '.join(details['verified_host_names'])
print(
u" platform: {platform}\n"
u" runnning: {running}\n"
u" dir_address: {dir_address}\n"
u" OR addresses: {or_addresses}\n"
u" location: {city_name}, {region_name}, {country_name}\n"
u" host names: {verified_host_names_formatted}\n"
u" AS: {as} ({as_name})\n"
u" last restarted: {last_restarted}\n"
u" last changed: {last_changed_address_or_port}\n"
u" last seen: {last_seen}\n"
u" probabilities: guard={guard_probability} middle={middle_probability} exit={exit_probability}\n"
u"".format(**details)
)
示例14: __call__
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def __call__(self, config: Config) -> Optional[str]:
token = config.oauth_token.split(':')[1]
fetched_users = await fetch_twitch_user(
config.channel,
oauth_token=token,
client_id=config.client_id,
)
assert fetched_users is not None
me, = fetched_users
fetched_users = await fetch_twitch_user(
self.username,
oauth_token=token,
client_id=config.client_id,
)
if not fetched_users:
msg = f'user {esc(self.username)} not found!'
return PRIVMSG.format(channel=config.channel, msg=msg)
target_user, = fetched_users
# if streamer wants to check the followage to their own channel
if me['id'] == target_user['id']:
msg = (
f"@{esc(target_user['login'])}, you can't check !followage "
f'to your own channel. But I appreciate your curiosity!'
)
return PRIVMSG.format(channel=config.channel, msg=msg)
follow_age_results = await fetch_twitch_user_follows(
from_id=target_user['id'],
to_id=me['id'],
oauth_token=token,
client_id=config.client_id,
)
if not follow_age_results:
msg = f'{esc(target_user["login"])} is not a follower!'
return PRIVMSG.format(channel=config.channel, msg=msg)
follow_age, = follow_age_results
now = datetime.datetime.utcnow()
date_of_follow = datetime.datetime.fromisoformat(
# twitch sends ISO date string with "Z" at the end,
# which python's fromisoformat method does not like
follow_age['followed_at'].rstrip('Z'),
)
delta = now - date_of_follow
msg = (
f'{esc(follow_age["from_name"])} has been following for '
f'{esc(naturaldelta(delta))}!'
)
return PRIVMSG.format(channel=config.channel, msg=msg)
# !followage -> valid, checks the caller
# !followage anthonywritescode -> valid, checks the user passed in payload
# !followage foo bar -> still valid, however the whole
# "foo bar" will be processed as a username
示例15: process_service_instance
# 需要导入模块: import humanize [as 别名]
# 或者: from humanize import naturaldelta [as 别名]
def process_service_instance(
self, service_instance: ServiceInstance
) -> BounceResults:
bounce_timers = self.setup_timers(service_instance)
if service_instance.enqueue_time is not None:
bounce_timers.processed_by_worker.record(
time.time() - service_instance.enqueue_time
)
human_bounce_by = humanize.naturaldelta(
datetime.timedelta(seconds=(time.time() - service_instance.bounce_by))
)
self.log.info(
f"{self.name} processing {service_instance.service}.{service_instance.instance} (bounce_by {human_bounce_by} ago)"
) # noqa E501
bounce_timers.setup_marathon.start()
return_code, bounce_again_in_seconds = deploy_marathon_service(
service=service_instance.service,
instance=service_instance.instance,
clients=self.marathon_clients,
soa_dir=marathon_tools.DEFAULT_SOA_DIR,
marathon_apps_with_clients=None,
)
bounce_timers.setup_marathon.stop()
self.log.info(
f"{self.name} setup marathon completed with exit code {return_code} for {service_instance.service}.{service_instance.instance}"
) # noqa E501
if bounce_again_in_seconds:
self.log.info(
f"{self.name} {service_instance.service}.{service_instance.instance} not in steady state so bouncing again in {bounce_again_in_seconds}"
) # noqa E501
else:
self.log.info(
f"{self.name} {service_instance.service}.{service_instance.instance} in steady state"
)
if service_instance.processed_count > 0:
bounce_timers.bounce_length.record(
time.time() - service_instance.bounce_start_time
)
return BounceResults(bounce_again_in_seconds, return_code)