Python humanize.naturaltime() Examples

The following are 30 code examples of humanize.naturaltime(). 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: cmds.py    From ecsctl with MIT License 6 votes vote down vote up
def get_task(ctx, cluster, sort_by):
    if not cluster:
        cluster = ctx.obj['cluster']
    bw = ctx.obj['bw']
    records = bw.get_tasks(cluster=cluster)
    if sort_by:
        records.sort(key=lambda r: jp(r, sort_by))
    out = []
    now = datetime.datetime.now(pytz.utc)
    for r in records:
        status = r['lastStatus']
        created_at = r['createdAt']
        task_id = display.simple_task(r['taskArn'])
        task_def = display.simple_task_definition(r['taskDefinitionArn'])
        age = humanize.naturaltime(now - created_at)
        row = (task_id, status, task_def, age)
        out.append(row)
    headers = ['TASK ID', 'STATUS', 'TASK DEFINITION', 'AGE']
    output = tabulate.tabulate(out, headers=headers, tablefmt='plain')
    click.echo(output) 
Example #2
Source File: status.py    From paasta with Apache License 2.0 6 votes vote down vote up
def format_kubernetes_replicaset_table(replicasets):
    rows = [("ReplicaSet Name", "Ready / Desired", "Created at what localtime")]
    for replicaset in replicasets:
        local_created_datetime = datetime.fromtimestamp(replicaset.create_timestamp)

        replica_status = f"{replicaset.ready_replicas}/{replicaset.replicas}"
        if replicaset.ready_replicas >= replicaset.replicas:
            replica_status = PaastaColors.green(replica_status)
        else:
            replica_status = PaastaColors.red(replica_status)

        rows.append(
            (
                replicaset.name,
                replica_status,
                "{} ({})".format(
                    local_created_datetime.strftime("%Y-%m-%dT%H:%M"),
                    humanize.naturaltime(local_created_datetime),
                ),
            )
        )

    return format_table(rows) 
Example #3
Source File: status.py    From paasta with Apache License 2.0 6 votes vote down vote up
def create_mesos_non_running_tasks_table(non_running_tasks):
    rows = []
    table_header = [
        "Mesos Task ID",
        "Host deployed to",
        "Deployed at what localtime",
        "Status",
    ]
    rows.append(table_header)

    for task in non_running_tasks or []:
        if task.deployed_timestamp is None:
            deployed_at_string = "Unknown"
        else:
            deployed_at = datetime.fromtimestamp(task.deployed_timestamp)
            deployed_at_string = "{} ({})".format(
                deployed_at.strftime("%Y-%m-%dT%H:%M"),
                humanize.naturaltime(deployed_at),
            )

        rows.append([task.id, task.hostname, deployed_at_string, task.state])
        rows.extend(format_tail_lines_for_mesos_task(task.tail_lines, task.id))

    table = format_table(rows)
    return [PaastaColors.grey(formatted_row) for formatted_row in table] 
Example #4
Source File: status.py    From paasta with Apache License 2.0 6 votes vote down vote up
def create_mesos_running_tasks_table(running_tasks):
    rows = []
    table_header = [
        "Mesos Task ID",
        "Host deployed to",
        "Ram",
        "CPU",
        "Deployed at what localtime",
    ]
    rows.append(table_header)
    for task in running_tasks or []:
        mem_string = get_mesos_task_memory_string(task)
        cpu_string = get_mesos_task_cpu_string(task)
        deployed_at = datetime.fromtimestamp(task.deployed_timestamp)
        deployed_at_string = "{} ({})".format(
            deployed_at.strftime("%Y-%m-%dT%H:%M"), humanize.naturaltime(deployed_at)
        )

        rows.append(
            [task.id, task.hostname, mem_string, cpu_string, deployed_at_string]
        )
        rows.extend(format_tail_lines_for_mesos_task(task.tail_lines, task.id))

    return format_table(rows) 
Example #5
Source File: cmds.py    From ecsctl with MIT License 6 votes vote down vote up
def get_services(ctx, cluster, sort_by):
    if not cluster:
        cluster = ctx.obj['cluster']
    bw = ctx.obj['bw']
    records = bw.get_services(cluster=cluster)
    if sort_by:
        records.sort(key=lambda r: jp(r, sort_by))
    out = []
    now = datetime.datetime.now(pytz.utc)
    for r in records:
        service_name = r['serviceName']
        task_def = display.simple_task_definition(r['taskDefinition'])
        status = r['status']
        created_at = r['createdAt']
        desired_count = r['desiredCount']
        running_count = r['runningCount']
        age = humanize.naturaltime(now - created_at)
        row = (service_name, task_def, desired_count,
               running_count, status, age)
        out.append(row)
    headers = ['NAME', 'TASK DEFINITION', 'DESIRED', 'RUNNING',
               'STATUS', 'AGE']
    output = tabulate.tabulate(out, headers=headers, tablefmt='plain')
    click.echo(output) 
Example #6
Source File: export_remote.py    From osm2vectortiles with MIT License 5 votes vote down vote up
def handle_message(tm2source, bucket, s3_url, body):
    msg = json.loads(body.decode('utf-8'))
    task_id = msg['id']
    mbtiles_file = task_id + '.mbtiles'

    source = 'tmsource://' + os.path.abspath(tm2source)
    sink = 'mbtiles://' + os.path.abspath(mbtiles_file)

    tilelive_cmd = []
    if msg['type'] == 'pyramid':
        tilelive_cmd = render_pyramid(msg, source, sink)
    elif msg['type'] == 'list':
        tilelive_cmd = render_list(msg, source, sink)
    else:
        raise ValueError("Message must be either of type pyramid or list")

    render_timeout = int(os.getenv('RENDER_TIMEOUT', 5 * 60))
    _, render_time = timing(subprocess.check_call, tilelive_cmd,
                            timeout=render_timeout)
    print('Render MBTiles: {}'.format(naturaltime(render_time)))

    _, optimize_time = timing(optimize_mbtiles, mbtiles_file)
    print('Optimize MBTiles: {}'.format(naturaltime(optimize_time)))

    _, upload_time = timing(upload_mbtiles, bucket, mbtiles_file)
    print('Upload MBTiles : {}'.format(naturaltime(upload_time)))

    download_link = s3_url(mbtiles_file)
    print('Uploaded {} to {}'.format(
        naturalsize(os.path.getsize(mbtiles_file)),
        download_link
    ))

    os.remove(mbtiles_file)

    return create_result_message(task_id, download_link, msg) 
Example #7
Source File: stats.py    From LibreNews-Server with GNU General Public License v3.0 5 votes vote down vote up
def time():
    return humanize.naturaltime(datetime.now(pytz.UTC) - starttime) 
Example #8
Source File: humanize.py    From clgen with GNU General Public License v3.0 5 votes vote down vote up
def Time(delta):
  return humanize_lib.naturaltime(delta) 
Example #9
Source File: models.py    From WatchPeopleCode with MIT License 5 votes vote down vote up
def format_start_time(self, countdown=True, start_time=True):
        if not self.scheduled_start_time or (not countdown and not start_time):
            return None

        if countdown:
            return humanize.naturaltime(datetime.utcnow() - self.scheduled_start_time) +\
                ((", " + datetime.strftime(self.scheduled_start_time, "%Y-%m-%d %H:%M UTC")) if start_time else "")
        else:
            return datetime.strftime(self.scheduled_start_time, "%Y-%m-%d %H:%M UTC") 
Example #10
Source File: file_total.py    From sarracenia with GNU General Public License v2.0 5 votes vote down vote up
def perform(self,parent):
        logger = parent.logger
        msg    = parent.msg

        import humanize
        import datetime
        from sarra.sr_util import timestr2flt

        if ( parent.file_total_bytecount==0 ) :
            logger.info("file_total: 0 files received: 0 msg/s, 0.0 bytes/s, lag: 0.0 s (RESET)"  )

        msgtime=timestr2flt(msg.pubtime)
        now=nowflt()

        parent.file_total_msgcount = parent.file_total_msgcount + 1

        lag=now-msgtime
        parent.file_total_lag = parent.file_total_lag + lag

        (method,psize,ptot,prem,pno) = msg.partstr.split(',')

        parent.file_total_bytecount = parent.file_total_bytecount + int(psize)
        
        #not time to report yet.
        if parent.file_total_interval > now-parent.file_total_last :
           return True

        logger.info("file_total: %3d files received: %5.2g msg/s, %s bytes/s, lag: %4.2g s" % ( 
            parent.file_total_msgcount,
	    parent.file_total_msgcount/(now-parent.file_total_start),
	    humanize.naturalsize(parent.file_total_bytecount/(now-parent.file_total_start),binary=True,gnu=True),
            parent.file_total_lag/parent.file_total_msgcount ))
        # Set the maximum age, in seconds, of a message to retrieve.

        if lag > parent.file_total_maxlag :
           logger.warn("total: Excessive lag! downloading too slowly/late %s behind" % 
               humanize.naturaltime(datetime.timedelta(seconds=lag)))

        parent.file_total_last = now

        return True 
Example #11
Source File: helpers.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def changed_on_humanized(self) -> str:
        return humanize.naturaltime(datetime.now() - self.changed_on) 
Example #12
Source File: dates.py    From simple-monitor-alert with MIT License 5 votes vote down vote up
def human_since(since, include_tz=False):
    tz = dateutil.tz.tzlocal() if include_tz else None
    return naturaltime(datetime.datetime.now(tz=tz) - dateutil.parser.parse(since)) 
Example #13
Source File: utils.py    From ok with Apache License 2.0 5 votes vote down vote up
def natural_time(date):
    """ Format a human-readable time difference (e.g. "6 days ago")"""
    if date.tzinfo:
        date = date.astimezone(pytz.utc).replace(tzinfo=None)
    now = dt.datetime.utcnow()
    return humanize.naturaltime(now - date) 
Example #14
Source File: app.py    From histsync with MIT License 5 votes vote down vote up
def format_time_added(self):
        if self.time_added:
            return humanize.naturaltime(datetime.utcnow() - self.time_added)
        else:
            return "[None]" 
Example #15
Source File: app.py    From histsync with MIT License 5 votes vote down vote up
def timesince(dt, default="just now"):
    """
    Jinja filter that takes a datetime and retuns the
    'human' version of time since said datetime.

    e.g. 28 minutes ago
    """

    now = datetime.utcnow()
    diff = now - dt

    return humanize.naturaltime(diff) 
Example #16
Source File: core.py    From rowboat with MIT License 5 votes vote down vote up
def on_guild_member_add(self, event):
        created = humanize.naturaltime(datetime.utcnow() - to_datetime(event.user.id))
        new = (
            event.config.new_member_threshold and
            (time.time() - to_unix(event.user.id)) < event.config.new_member_threshold
        )

        self.log_action(Actions.GUILD_MEMBER_ADD, event, new=' :new:' if new else '', created=created) 
Example #17
Source File: models.py    From wharf with GNU Affero General Public License v3.0 5 votes vote down vote up
def nice_when(self):
        return humanize.naturaltime(datetime.datetime.now(datetime.timezone.utc) - self.when) 
Example #18
Source File: post_total.py    From sarracenia with GNU General Public License v2.0 5 votes vote down vote up
def perform(self,parent):
        logger = parent.logger
        msg    = parent.msg

        import calendar
        import humanize
        import datetime
        from sarra.sr_util import timestr2flt

        if parent.post_total_msgcount == 0:
            logger.info("post_total: 0 messages posted: 0 msg/s, 0.0 bytes/s, lag: 0.0 s (RESET)"  )

        msgtime=timestr2flt(msg.pubtime)
        now=nowflt()

        parent.post_total_msgcount = parent.post_total_msgcount + 1

        lag=now-msgtime
        parent.post_total_lag = parent.post_total_lag + lag

        #(method,psize,ptot,prem,pno) = msg.partstr.split(',')
        #parent.post_total_bytecount = parent.post_total_bytecount + int(psize)
        
        #not time to report yet.
        if parent.post_total_interval > now-parent.post_total_last :
           return True

        logger.info("post_total: %3d messages posted: %5.2g msg/s, lag: %4.2g s" % ( 
            parent.post_total_msgcount,
	    parent.post_total_msgcount/(now-parent.post_total_start),
            parent.post_total_lag/parent.post_total_msgcount ))
        # Set the maximum age, in seconds, of a message to retrieve.

        if lag > parent.post_total_maxlag :
           logger.warn("total: Excessive lag! Messages posted %s " % 
               humanize.naturaltime(datetime.timedelta(seconds=lag)))

        parent.post_total_last = now

        return True 
Example #19
Source File: msg_speedo.py    From sarracenia with GNU General Public License v2.0 5 votes vote down vote up
def on_message(self,parent):
        logger = parent.logger
        msg    = parent.msg

        import calendar
        import humanize
        import datetime

        msgtime=timestr2flt(msg.pubtime)
        now=nowflt()

        parent.msg_speedo_msgcount = parent.msg_speedo_msgcount + 1

        (method,psize,ptot,prem,pno) = msg.partstr.split(',')

        parent.msg_speedo_bytecount = parent.msg_speedo_bytecount + int(psize)
        
        #not time to report yet.
        if parent.msg_speedo_interval > now-parent.msg_speedo_last :
           return True

        lag=now-msgtime

        logger.info("speedo: %3d messages received: %5.2g msg/s, %s bytes/s, lag: %4.2g s" % ( 
            parent.msg_speedo_msgcount,
	    parent.msg_speedo_msgcount/(now-parent.msg_speedo_last),
	    humanize.naturalsize(parent.msg_speedo_bytecount/(now-parent.msg_speedo_last),binary=True,gnu=True),
            lag))

        # Set the maximum age, in seconds, of a message to retrieve.

        if lag > parent.msg_speedo_maxlag :
           logger.warn("speedo: Excessive lag! Messages posted %s " % 
               humanize.naturaltime(datetime.timedelta(seconds=lag)))

        parent.msg_speedo_last = now
        parent.msg_speedo_msgcount = 0
        parent.msg_speedo_bytecount = 0

        return True 
Example #20
Source File: afk.py    From userbot with GNU General Public License v3.0 5 votes vote down vote up
def subtract_time(start, end):
    """Get humanized time"""
    subtracted = humanize.naturaltime(start - end)
    return str(subtracted) 
Example #21
Source File: filters.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def ago_filter(dt):
    """
    Format a datetime using humanize.naturaltime, "ago"

    :param dt: datetime to compare to now
    :type dt: datetime.datetime
    :return: ago string
    :rtype: str
    """
    if dt == '' or dt is None or isinstance(dt, Undefined):
        return ''
    return naturaltime(dtnow() - dt) 
Example #22
Source File: GoPro.py    From gopro with MIT License 5 votes vote down vote up
def time_offset(self):
        if self.ok:
            now = datetime.datetime.today()
            gp_time = self.datetime
            if now > gp_time:
                multiplier = 1
                time_offset = now - gp_time
            else:
                multiplier = -1
                time_offset = gp_time - now
            time_offset = time_offset.total_seconds() * multiplier
            self._status['time_offset'] = humanize.naturaltime(time_offset)
            return time_offset 
Example #23
Source File: frontend.py    From ga4gh-server with Apache License 2.0 5 votes vote down vote up
def getNaturalUptime(self):
        """
        Returns the uptime in a human-readable format.
        """
        return humanize.naturaltime(self.startupTime) 
Example #24
Source File: rollback.py    From paasta with Apache License 2.0 5 votes vote down vote up
def list_previous_commits(service, deploy_groups, any_given_deploy_groups, git_shas):
    def format_timestamp(tstamp):
        return naturaltime(datetime_from_utc_to_local(parse_timestamp(tstamp)))

    print("Below is a list of recent commits:")
    git_shas = sorted(git_shas.items(), key=lambda x: x[1], reverse=True)[:10]
    rows = [("Timestamp -- UTC", "Human time", "deploy_group", "Git SHA")]
    for sha, (timestamp, deploy_group) in git_shas:
        rows.extend([(timestamp, format_timestamp(timestamp), deploy_group, sha)])
    for line in format_table(rows):
        print(line)
    if len(git_shas) >= 2:
        sha, (timestamp, deploy_group) = git_shas[1]
        deploy_groups_arg_line = (
            "-l %s " % ",".join(deploy_groups) if any_given_deploy_groups else ""
        )
        print(
            "\nFor example, to use the second to last commit from {} used on {}, run:".format(
                format_timestamp(timestamp), PaastaColors.bold(deploy_group)
            )
        )
        print(
            PaastaColors.bold(
                f"    paasta rollback -s {service} {deploy_groups_arg_line}-k {sha}"
            )
        ) 
Example #25
Source File: status.py    From paasta with Apache License 2.0 5 votes vote down vote up
def format_marathon_task_table(tasks):
    rows = [
        ("Mesos Task ID", "Host deployed to", "Deployed at what localtime", "Health")
    ]
    for task in tasks:
        local_deployed_datetime = datetime.fromtimestamp(task.deployed_timestamp)
        if task.host is not None:
            hostname = f"{task.host}:{task.port}"
        else:
            hostname = "Unknown"

        if task.is_healthy is None:
            health_check_status = PaastaColors.grey("N/A")
        elif task.is_healthy:
            health_check_status = PaastaColors.green("Healthy")
        else:
            health_check_status = PaastaColors.red("Unhealthy")

        rows.append(
            (
                task.id,
                hostname,
                "{} ({})".format(
                    local_deployed_datetime.strftime("%Y-%m-%dT%H:%M"),
                    humanize.naturaltime(local_deployed_datetime),
                ),
                health_check_status,
            )
        )

    return format_table(rows) 
Example #26
Source File: status.py    From paasta with Apache License 2.0 5 votes vote down vote up
def build_smartstack_backends_table(backends: Iterable[Any]) -> List[str]:
    rows: List[Tuple[str, ...]] = [("Name", "LastCheck", "LastChange", "Status")]
    for backend in backends:
        if backend.status == "UP":
            status = PaastaColors.default(backend.status)
        elif backend.status == "DOWN":
            status = PaastaColors.red(backend.status)
        elif backend.status == "MAINT":
            status = PaastaColors.grey(backend.status)
        else:
            status = PaastaColors.yellow(backend.status)

        if backend.check_duration is None:
            check_duration = ""
        else:
            check_duration = str(backend.check_duration)

        row: Tuple[str, ...] = (
            f"{backend.hostname}:{backend.port}",
            f"{backend.check_status}/{backend.check_code} in {check_duration}ms",
            humanize.naturaltime(timedelta(seconds=backend.last_change)),
            status,
        )

        if not backend.has_associated_task:
            row = tuple(
                PaastaColors.grey(remove_ansi_escape_sequences(col)) for col in row
            )

        rows.append(row)

    return format_table(rows) 
Example #27
Source File: mesos_tools.py    From paasta with Apache License 2.0 5 votes vote down vote up
def get_first_status_timestamp_string(task: Task) -> str:
    """Gets the first status timestamp from a task id and returns a human
    readable string with the local time and a humanized duration:
    ``2015-01-30T08:45 (an hour ago)``
    """
    first_status_timestamp = get_first_status_timestamp(task)
    if first_status_timestamp is None:
        return "Unknown"
    else:
        first_status_datetime = datetime.datetime.fromtimestamp(first_status_timestamp)
        return "{} ({})".format(
            first_status_datetime.strftime("%Y-%m-%dT%H:%M"),
            humanize.naturaltime(first_status_datetime),
        ) 
Example #28
Source File: lnd_process.py    From node-launcher with MIT License 5 votes vote down vote up
def process_output_line(self, line: str):
        if 'Waiting for wallet encryption password' in line:
            self.update_status(NodeStatus.UNLOCK_READY)
        elif 'Waiting for chain backend to finish sync' in line:
            self.set_icon_color.emit('blue')
            self.update_status(NodeStatus.SYNCING)
        elif 'Unable to synchronize wallet to chain' in line:
            self.terminate()
            self.restart_process()
        elif 'Unable to complete chain rescan' in line:
            self.terminate()
            self.restart_process()
        elif 'Starting HTLC Switch' in line:
            self.set_icon_color.emit('green')
            self.update_status(NodeStatus.SYNCED)
            self.notification.emit(
                'LND is ready',
                'Open Joule or Zap',
                QSystemTrayIcon.Information
            )
        elif 'Caught up to height' in line:
            new_height = int(line.split(' ')[-1])
            timestamp = line.split('[INF]')[0].strip()
            new_timestamp = datetime.strptime(
                timestamp,
                '%Y-%m-%d %H:%M:%S.%f'
            )
            if self.old_height is not None:
                change = new_height - self.old_height
                if change:
                    timestamp_change = new_timestamp - self.old_timestamp
                    total_left = 600000 - new_height
                    time_left = (total_left / change) * timestamp_change
                    humanized = humanize.naturaltime(-time_left)
                    self.sync_progress.emit(
                        f'ETA: {humanized}, caught up to height {new_height}'
                    )

            self.old_height = new_height
            self.old_timestamp = new_timestamp 
Example #29
Source File: __init__.py    From notifications-admin with MIT License 5 votes vote down vote up
def naturaltime_without_indefinite_article(date):
    return re.sub(
        'an? (.*) ago',
        lambda match: '1 {} ago'.format(match.group(1)),
        humanize.naturaltime(date),
    ) 
Example #30
Source File: steam.py    From hawthorne with GNU Lesser General Public License v3.0 5 votes vote down vote up
def created(value):
  user = api.ISteamUser.GetPlayerSummaries(steamids=value)['response']
  timestamp = user['players'][0]['timecreated']

  return humanize.naturaltime(datetime.datetime.fromtimestamp(timestamp))