Python humanize.naturaldelta() Examples
The following are 21
code examples of humanize.naturaldelta().
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.
You may also want to check out all available functions/classes of the module
humanize
, or try the search function
.
Example #1
Source File: utilities.py From rowboat with MIT License | 6 votes |
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()), ))
Example #2
Source File: pandas_execution_stats.py From pandas-log with MIT License | 6 votes |
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
Example #3
Source File: infractions.py From rowboat with MIT License | 6 votes |
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')
Example #4
Source File: core.py From rowboat with MIT License | 5 votes |
def command_uptime(self, event): event.msg.reply('Rowboat was started {}'.format( humanize.naturaldelta(datetime.utcnow() - self.startup) ))
Example #5
Source File: carml_relay.py From carml with The Unlicense | 5 votes |
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) )
Example #6
Source File: humanize.py From clgen with GNU General Public License v3.0 | 5 votes |
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)
Example #7
Source File: utilities.py From rowboat with MIT License | 5 votes |
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 ))
Example #8
Source File: infractions.py From rowboat with MIT License | 5 votes |
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)
Example #9
Source File: cli.py From stdpopsim with GNU General Public License v3.0 | 5 votes |
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))
Example #10
Source File: core.py From rowboat with MIT License | 5 votes |
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)
Example #11
Source File: models.py From twtxt with MIT License | 5 votes |
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)
Example #12
Source File: twhttp.py From twtxt with MIT License | 5 votes |
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)
Example #13
Source File: cli.py From tsinfer with GNU General Public License v3.0 | 5 votes |
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)
Example #14
Source File: monitor.py From mkctf with GNU General Public License v3.0 | 4 votes |
def worker_routine(worker_id, monitor): '''Represent a monitoring worker ''' while True: # get next task out of the queue task = await monitor.task_queue.get() if task is None: await monitor.print(f"[{worker_id}]: exiting gracefully") break # process task await monitor.print(f"[{worker_id}]: waiting for {task.slug} to reach schedule: {naturaldelta(task.countdown)} remaining") await task.is_ready() await monitor.print(f"[{worker_id}]: running healthcheck for {task.slug}") try: report = await task.run() except Exception as exc: report = None await monitor.post(worker_id, task.slug, False) await monitor.print(f"[{worker_id}]: an exception occured while running healthcheck for {task.slug}: {exc}") else: await monitor.post(worker_id, task.slug, report['healthy']) # inject exploit back in queue if needed if task.should_run_again: await monitor.task_queue.put(task) # notify the queue that the task has been processed monitor.task_queue.task_done() # print report if report: stdout = b'' stderr = b'' health = 'healthy' if report['healthy'] else 'DEAD' sep = ('=' * 80) + '\n' text = sep text += f"[{worker_id}]: reporting for {task.slug}\n" text += f"[{worker_id}]: - state: {health}\n" text += f"[{worker_id}]: - check duration: {naturaldelta(task.duration)}\n" if not report['healthy']: stdout = f"----------------[{task.slug}:STDOUT]----------------\n" stdout = stdout.encode() + report['stdout'] stderr = f"----------------[{task.slug}:STDERR]----------------\n" stderr = stderr.encode() + report['stderr'] text = text.encode() + stdout + stderr + sep.encode() await monitor.print(text, raw=True) # ============================================================================= # CLASSES # =============================================================================
Example #15
Source File: mark_for_deployment.py From paasta with Apache License 2.0 | 4 votes |
def schedule_paasta_status_reminder(self): timeout_percentage_before_reminding = 75 def waiting_on_to_status(waiting_on): if waiting_on is None: return [ f"`paasta status --service {self.service} --{self.deploy_group}` -vv" ] commands = [] for cluster, queue in waiting_on.items(): queue_length = len(queue) if queue_length == 0: continue else: instances = [q.get_instance() for q in queue] commands.append( f"`paasta status --service {self.service} --cluster {cluster} --instance {','.join(instances)} -vv`" ) return commands def times_up(): try: if self.state == "deploying": human_max_deploy_time = humanize.naturaldelta( datetime.timedelta(seconds=self.timeout) ) status_commands = "\n".join( waiting_on_to_status(self.progress.waiting_on) ) self.notify_users( ( f"It has been {timeout_percentage_before_reminding}% of the maximum deploy time ({human_max_deploy_time}), " "it probably should have finished by now. Is it stuck?\n\n" "Try running this command to see the status of the deploy:\n" f"{status_commands}" ) ) except Exception as e: log.error( f"Non-fatal exception encountered when processing the status reminder: {e}" ) def schedule_callback(): time_to_notify = self.timeout * (timeout_percentage_before_reminding / 100) self.paasta_status_reminder_handle = self.event_loop.call_later( time_to_notify, times_up ) try: self.event_loop.call_soon_threadsafe(schedule_callback) except Exception as e: log.error( f"Non-fatal error encountered scheduling the status reminder callback: {e}" )
Example #16
Source File: infractions.py From rowboat with MIT License | 4 votes |
def infraction_search(self, event, query=None): q = (Infraction.guild_id == event.guild.id) if query and isinstance(query, list) and isinstance(query[0], DiscoUser): query = query[0].id elif query: query = ' '.join(query) if query and (isinstance(query, int) or query.isdigit()): q &= ( (Infraction.id == int(query)) | (Infraction.user_id == int(query)) | (Infraction.actor_id == int(query))) elif query: q &= (Infraction.reason ** query) user = User.alias() actor = User.alias() infractions = 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(q).order_by(Infraction.created_at.desc()).limit(6) tbl = MessageTable() tbl.set_header('ID', 'Created', 'Type', 'User', 'Moderator', 'Active', 'Reason') for inf in infractions: type_ = {i.index: i for i in Infraction.Types.attrs}[inf.type_] reason = inf.reason or '' if len(reason) > 256: reason = reason[:256] + '...' if inf.active: active = 'yes' if inf.expires_at: active += ' (expires in {})'.format(humanize.naturaldelta(inf.expires_at - datetime.utcnow())) else: active = 'no' tbl.add( inf.id, inf.created_at.isoformat(), str(type_), unicode(inf.user), unicode(inf.actor), active, clamp(reason, 128) ) event.msg.reply(tbl.compile())
Example #17
Source File: infractions.py From rowboat with MIT License | 4 votes |
def tempmute(self, event, user, duration=None, reason=None): if not duration and reason: duration = parse_duration(reason.split(' ')[0], safe=True) if duration: if ' ' in reason: reason = reason.split(' ', 1)[-1] else: reason = None elif duration: duration = parse_duration(duration) member = event.guild.get_member(user) if member: self.can_act_on(event, member.id) if not event.config.mute_role: raise CommandFail('mute is not setup on this server') if event.config.mute_role in member.roles: raise CommandFail(u'{} is already muted'.format(member.user)) # If we have a duration set, this is a tempmute if duration: # Create the infraction Infraction.tempmute(self, event, member, reason, duration) self.queue_infractions() self.confirm_action(event, maybe_string( reason, u':ok_hand: {u} is now muted for {t} (`{o}`)', u':ok_hand: {u} is now muted for {t}', u=member.user, t=humanize.naturaldelta(duration - datetime.utcnow()), )) else: existed = False # If the user is already muted check if we can take this from a temp # to perma mute. if event.config.mute_role in member.roles: existed = Infraction.clear_active(event, member.id, [Infraction.Types.TEMPMUTE]) # The user is 100% muted and not tempmuted at this point, so lets bail if not existed: raise CommandFail(u'{} is already muted'.format(member.user)) Infraction.mute(self, event, member, reason) existed = u' [was temp-muted]' if existed else '' self.confirm_action(event, maybe_string( reason, u':ok_hand: {u} is now muted (`{o}`)' + existed, u':ok_hand: {u} is now muted' + existed, u=member.user, )) else: raise CommandFail('invalid user')
Example #18
Source File: workers.py From paasta with Apache License 2.0 | 4 votes |
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)
Example #19
Source File: bot.py From twitch-chat-bot with MIT License | 4 votes |
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
Example #20
Source File: utilities.py From rowboat with MIT License | 4 votes |
def server(self, event, guild_id=None): guild = self.state.guilds.get(guild_id) if guild_id else event.guild if not guild: raise CommandFail('invalid server') content = [] content.append(u'**\u276F Server Information**') created_at = to_datetime(guild.id) content.append(u'Created: {} ago ({})'.format( humanize.naturaldelta(datetime.utcnow() - created_at), created_at.isoformat(), )) content.append(u'Members: {}'.format(len(guild.members))) content.append(u'Features: {}'.format(', '.join(guild.features) or 'none')) content.append(u'\n**\u276F Counts**') text_count = sum(1 for c in guild.channels.values() if not c.is_voice) voice_count = len(guild.channels) - text_count content.append(u'Roles: {}'.format(len(guild.roles))) content.append(u'Text: {}'.format(text_count)) content.append(u'Voice: {}'.format(voice_count)) content.append(u'\n**\u276F Members**') status_counts = defaultdict(int) for member in guild.members.values(): if not member.user.presence: status = Status.OFFLINE else: status = member.user.presence.status status_counts[status] += 1 for status, count in sorted(status_counts.items(), key=lambda i: str(i[0]), reverse=True): content.append(u'<{}> - {}'.format( STATUS_EMOJI[status], count )) embed = MessageEmbed() if guild.icon: embed.set_thumbnail(url=guild.icon_url) embed.color = get_dominant_colors_guild(guild) embed.description = '\n'.join(content) event.msg.reply('', embed=embed)
Example #21
Source File: utilities.py From rowboat with MIT License | 4 votes |
def trigger_reminder(self, reminder): message = reminder.message_id channel = self.state.channels.get(message.channel_id) if not channel: self.log.warning('Not triggering reminder, channel %s was not found!', message.channel_id) reminder.delete_instance() return msg = channel.send_message(u'<@{}> you asked me at {} ({} ago) to remind you about: {}'.format( message.author_id, reminder.created_at, humanize.naturaldelta(reminder.created_at - datetime.utcnow()), S(reminder.content) )) # Add the emoji options msg.add_reaction(SNOOZE_EMOJI) msg.add_reaction(GREEN_TICK_EMOJI) try: mra_event = self.wait_for_event( 'MessageReactionAdd', message_id=msg.id, conditional=lambda e: ( (e.emoji.name == SNOOZE_EMOJI or e.emoji.id == GREEN_TICK_EMOJI_ID) and e.user_id == message.author_id ) ).get(timeout=30) except gevent.Timeout: reminder.delete_instance() return finally: # Cleanup msg.delete_reaction(SNOOZE_EMOJI) msg.delete_reaction(GREEN_TICK_EMOJI) if mra_event.emoji.name == SNOOZE_EMOJI: reminder.remind_at = datetime.utcnow() + timedelta(minutes=20) reminder.save() msg.edit(u'Ok, I\'ve snoozed that reminder for 20 minutes.') return reminder.delete_instance()