How to use the humanfriendly.format_timespan function in humanfriendly

To help you get started, we’ve selected a few humanfriendly examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xolox / python-humanfriendly / humanfriendly / tests.py View on Github external
assert '2 days' == humanfriendly.format_timespan(day * 2)
        assert '1 week' == humanfriendly.format_timespan(week)
        assert '2 weeks' == humanfriendly.format_timespan(week * 2)
        assert '1 year' == humanfriendly.format_timespan(year)
        assert '2 years' == humanfriendly.format_timespan(year * 2)
        assert '6 years, 5 weeks, 4 days, 3 hours, 2 minutes and 500 milliseconds' == \
            humanfriendly.format_timespan(year * 6 + week * 5 + day * 4 + hour * 3 + minute * 2 + 0.5, detailed=True)
        assert '1 year, 2 weeks and 3 days' == \
            humanfriendly.format_timespan(year + week * 2 + day * 3 + hour * 12)
        # Make sure milliseconds are never shown separately when detailed=False.
        # https://github.com/xolox/python-humanfriendly/issues/10
        assert '1 minute, 1 second and 100 milliseconds' == humanfriendly.format_timespan(61.10, detailed=True)
        assert '1 minute and 1.1 second' == humanfriendly.format_timespan(61.10, detailed=False)
        # Test for loss of precision as reported in issue 11:
        # https://github.com/xolox/python-humanfriendly/issues/11
        assert '1 minute and 0.3 seconds' == humanfriendly.format_timespan(60.300)
        assert '5 minutes and 0.3 seconds' == humanfriendly.format_timespan(300.300)
        assert '1 second and 15 milliseconds' == humanfriendly.format_timespan(1.015, detailed=True)
        assert '10 seconds and 15 milliseconds' == humanfriendly.format_timespan(10.015, detailed=True)
        # Test the datetime.timedelta support:
        # https://github.com/xolox/python-humanfriendly/issues/27
        now = datetime.datetime.now()
        then = now - datetime.timedelta(hours=23)
        assert '23 hours' == humanfriendly.format_timespan(now - then)
github xolox / python-executor / executor / cli.py View on Github external
def __init__(self, command, timeout):
        """
        Initialize a :class:`CommandTimedOut` object.

        :param command: The command that timed out (an
                        :class:`~executor.ExternalCommand` object).
        :param timeout: The timeout that was exceeded (a number).
        """
        super(CommandTimedOut, self).__init__(
            command=command,
            error_message=format(
                "External command exceeded timeout of %s: %s",
                format_timespan(timeout),
                quote(command.command_line),
            ),
github FuelRats / pipsqueak3 / src / packages / utils / ratlib.py View on Github external
def duration(time: datetime.timedelta) -> str:
    """
    Converts a timedelta into a more friendly human readable string, such as
    '5m 3w 4d ago'
    Args:
        time: (timedelta) time.

    Returns: (str) Easier-to-read time.

    """
    if not isinstance(time, datetime.timedelta):
        raise TypeError("ratlib.duration method requires a datetime or timedelta.")

    return humanfriendly.format_timespan(time, detailed=False, max_units=2)
github adamrehn / ue4-docker / ue4docker / infrastructure / ImageBuilder.py View on Github external
if self.dryRun == True:
			print(command)
			self.logger.action('Completed dry run for image "{}".'.format(image), newline=False)
			return
		
		# Attempt to process the image using the supplied command
		startTime = time.time()
		exitCode = subprocess.call(command)
		endTime = time.time()
		
		# Determine if processing succeeded
		if exitCode == 0:
			self.logger.action('{} image "{}" in {}'.format(
				actionPastTense.capitalize(),
				image,
				humanfriendly.format_timespan(endTime - startTime)
			), newline=False)
		else:
			raise RuntimeError('failed to {} image "{}".'.format(actionPresentTense, image))
github arielbeje / uBot / utils / punishmentshelper.py View on Github external
async def ensure_unban(server: discord.Guild, member: Union[discord.Member, discord.User],
                       duration: int, partialDuration: bool = False):
    """
    Sleeps for the given duration, then unbans the member.
    Also removes the ban row from the db.
    """
    await asyncio.sleep(duration)
    reason = "Temporary ban " + (f"of {humanfriendly.format_timespan(duration)} " if not partialDuration else "") + "ended."
    await server.unban(member, reason=reason)
    await sql.execute("DELETE FROM bans WHERE serverid=? AND userid=?",
                      str(server.id), str(member.id))
github parttimenerd / temci / temci / run / run_driver.py View on Github external
def __init__(self, cmd: str, timeout: float, out: str, err: str, ret_code: int):
        from temci.report.rundata import RecordedProgramError
        super().__init__(RecordedProgramError("The following run command hit a timeout after {}: {}"
                                              .format(humanfriendly.format_timespan(timeout), cmd), out, err,
                                              ret_code))
github parttimenerd / temci / temci / report / report.py View on Github external
"""
            inner_html += self._comparison_for_prop(prop)
        for single in self.stats.singles:
            inner_html += """<div class="block">"""
            inner_html += self._extended_summary(single, with_title=True, title_level=2,
                                                 title_class="page-header") + """</div>"""
        for pair in self.stats.pairs:
            inner_html += """<div class="block">"""
            inner_html += self._extended_summary(pair, with_title=True, title_level=2,
                                                 title_class="page-header") + """</div>"""
        self._write(html.format(timespan=hf.format_timespan(time.time() - start_time), **locals()))
        logging.info("Finished generating html")
        logging.info("Generate images...")
        self._process_hist_cache(self._hist_async_img_cache.values(), "Generate images")
        self._process_boxplot_cache(self._boxplot_async_cache.values(), "Generate box plots")
        self._write(html.format(timespan=hf.format_timespan(time.time() - start_time), **locals()))
        if self.misc["gen_pdf"] or self.misc["gen_tex"]:
            strs = (["tex"] if self.misc["gen_tex"] else []) + (["pdf"] if self.misc["gen_pdf"] else [])
            self._process_hist_cache(self._hist_async_misc_cache.values(), "Generate {}".format(join_strs(strs)))
github mozilla-services / socorro / webapp-django / crashstats / crashstats / templatetags / jinja_helpers.py View on Github external
)

    try:
        seconds = int(seconds)
    except (ValueError, TypeError):
        # ValueErrors happen when `seconds` is not a number.
        # TypeErrors happen when you try to convert a None to an integer.

        # Bail, but note how it's NOT marked as safe.
        # That means that if `seconds` is literally '
github xolox / python-humanfriendly / humanfriendly / cli.py View on Github external
def print_formatted_timespan(value):
    """Print a human readable timespan."""
    output(format_timespan(float(value)))
github xolox / python-executor / executor / cli.py View on Github external
def apply_fudge_factor(fudge_factor):
    """
    Apply the requested scheduling fudge factor.

    :param fudge_factor: The maximum number of seconds to sleep (a number).

    Previous implementations of the fudge factor interrupt used UNIX signals
    (specifically ``SIGUSR1``) but the use of this signal turned out to be
    sensitive to awkward race conditions and it wasn't very cross platform, so
    now the creation of a regular file is used to interrupt the fudge factor.
    """
    if fudge_factor:
        timer = Timer()
        logger.debug("Calculating fudge factor based on user defined maximum (%s) ..",
                     format_timespan(fudge_factor))
        fudged_sleep_time = fudge_factor * random.random()
        logger.info("Sleeping for %s because of user defined fudge factor ..",
                    format_timespan(fudged_sleep_time))
        interrupt_file = get_lock_path(INTERRUPT_FILE)
        while timer.elapsed_time &lt; fudged_sleep_time:
            if os.path.isfile(interrupt_file):
                logger.info("Fudge factor sleep was interrupted! (%s exists)",
                            interrupt_file)
                break
            time_to_sleep = min(1, fudged_sleep_time - timer.elapsed_time)
            if time_to_sleep &gt; 0:
                time.sleep(time_to_sleep)
        else:
            logger.info("Finished sleeping because of fudge factor (took %s).", timer)