Format ISO-8601 duration string.

    Args:
        __timedelta: Duration to process
    Returns:
        ISO-8601 representation of duration
349150
def format_delta(__timedelta: datetime.timedelta) -> str:
    
    if __timedelta == datetime.timedelta(0):
        return ''
    days_s = '{}D'.format(__timedelta.days) if __timedelta.days else ''
    hours, minutes = divmod(__timedelta.seconds, 3600)
    minutes, seconds = divmod(minutes, 60)
    hours_s = '{:02d}H'.format(hours) if hours else ''
    minutes_s = '{:02d}M'.format(minutes) if minutes else ''
    seconds_s = '{:02d}S'.format(seconds) if seconds else ''
    return 'P{}{}{}{}{}'.format(days_s,
                                'T' if hours or minutes or seconds else '',
                                hours_s, minutes_s, seconds_s)
902501
def _convert_timedelta_to_seconds(timedelta):
    

    days_in_seconds = timedelta.days * 24 * 3600
    return int((timedelta.microseconds + (timedelta.seconds + days_in_seconds) * 10 ** 6) / 10 ** 6)
533490
def timedelta_seconds(timedelta):
    """"""
    return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds")
            else timedelta.days * 24 * 3600 + timedelta.seconds +
                 timedelta.microseconds / 1000000.)
975449
public static String formatDuration(long durationMs){
        Period period = Period.seconds((int)(durationMs/1000L));
        Period p2 = period.normalizedStandard(PeriodType.yearMonthDayTime());

        PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendYears()
                .appendSuffix(" yr ")
                .appendMonths()
                .appendSuffix(" months ")
                .appendDays()
                .appendSuffix(" days ")
                .appendHours()
                .appendSuffix(" hr ")
                .appendMinutes()
                .appendSuffix(" min ")
                .appendSeconds()
                .appendSuffix(" sec")
                .toFormatter();

        return formatter.print(p2);
    }
1161780
def duration(self):
        
        if self.time_end is None or self.time_start is None:
            return timedelta(seconds=0)
        else:
            return self.time_end - self.time_start
1369244
def fix_timedelta_repr(func):
    
    # We don't need to do anything if we're not on 3.7 or above
    if version < (3, 7):
        return func

    def fix_timedelta(match):
        values = match.group(1).split(", ")
        param_repr = ", ".join(
            "{}={}".format(param, value)
            for param, value in zip(("days", "seconds", "microseconds"), values)
            if value != "0"
        )

        # If we have a zero length timedelta it should be represented as
        # timedelta(0), i.e. without named parameters
        if not param_repr:
            param_repr = "0"

        return "timedelta({})".format(param_repr)

    func.__doc__ = re.sub(r"timedelta\(([^)]+)\)", fix_timedelta, func.__doc__)
    return func
1366987
def from_timedelta(cls, timedelta):
        """"""
        from math import ceil
        units = ceil(timedelta.total_seconds() / cls.time_unit)
        return cls.create(units)
903212
def parse_duration(line):
    
    DAYS, SECS = {'D': 1, 'W': 7}, {'S': 1, 'M': 60, 'H': 3600}
    sign, i = 1, 0
    if line[i] in '-+':
        if line[i] == '-':
            sign = -1
        i += 1
    if line[i] != 'P':
        raise parse.ParseError()
    i += 1
    days, secs = 0, 0
    while i < len(line):
        if line[i] == 'T':
            i += 1
            if i == len(line):
                break
        j = i
        while line[j].isdigit():
            j += 1
        if i == j:
            raise parse.ParseError()
        val = int(line[i:j])
        if line[j] in DAYS:
            days += val * DAYS[line[j]]
            DAYS.pop(line[j])
        elif line[j] in SECS:
            secs += val * SECS[line[j]]
            SECS.pop(line[j])
        else:
            raise parse.ParseError()
        i = j + 1
    return timedelta(sign * days, sign * secs)
904569
def compile_timedelta(rule):
    
    if isinstance(rule.value, datetime.timedelta):
        return rule
    try:
        # Try numeric type
        return TimedeltaRule(datetime.timedelta(seconds = int(rule.value)))
    except:
        pass
    # Try RFC3339 timestamp string
    res = DURATION_RE.match(str(rule.value))
    if res is not None:
        days, hours, minutes, seconds = (int(n or 0) for n in res.group('days','hrs','mins','secs'))
        return TimedeltaRule(datetime.timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds))
    raise ValueError("Wrong timedelta format '{}'".format(rule.value))
905401
def parse_timedelta(ev):
    

    chunks = ev['event-duration'].split()
    tdargs = {}
    for c in chunks:
        try:
            m = TIME_MULTIPLIERS[c[-1]]
            val = int(c[:-1])
            tdargs[m] = val
        except KeyError:
            log.error("""Unknown time multiplier '%s' value in the \
'event-duration' field in the '%s' event. Supported multipliers \
are: '%s'.""" % (c, ev['title'], ' '.join(TIME_MULTIPLIERS)))
            raise RuntimeError("Unknown time multiplier '%s'" % c)
        except ValueError:
            log.error("""Unable to parse '%s' value in the 'event-duration' \
field in the '%s' event.""" % (c, ev['title']))
            raise ValueError("Unable to parse '%s'" % c)


    return timedelta(**tdargs)
377001
def get_formatted_time(seconds: float) -> str:
    
    seconds = round(seconds)
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    return '{:d}:{:02d}:{:02d}'.format(h, m, s)
384104
def str_to_timedelta(input_str):
    
    try:
        input_str = input_str.replace(' ', ':')
    except (TypeError, AttributeError):
        from configman.converters import to_str
        raise TypeError('%s should have been a string' % to_str(input_str))
    days, hours, minutes, seconds = 0, 0, 0, 0
    details = input_str.split(':')
    if len(details) >= 4:
        days = int(details[-4])
    if len(details) >= 3:
        hours = int(details[-3])
    if len(details) >= 2:
        minutes = int(details[-2])
    if len(details) >= 1:
        seconds = int(details[-1])
    return datetime.timedelta(days=days,
                              hours=hours,
                              minutes=minutes,
                              seconds=seconds)
985391
def humanize_time_since(timestamp=None):
    
    timeDiff = datetime.datetime.now() - timestamp
    days = timeDiff.days
    hours = timeDiff.seconds / 3600
    minutes = timeDiff.seconds % 3600 / 60
    seconds = timeDiff.seconds % 3600 % 60

    str = ""
    if days > 0:
        if days == 1:
            t_str = "day"
        else:
            t_str = "days"
        str += "{0} {1}".format(days, t_str)
        return str
    elif hours > 0:
        if hours == 1:
            t_str = "hour"
        else:
            t_str = "hours"
        str += "{0} {1}".format(hours, t_str)
        return str
    elif minutes > 0:
        if minutes == 1:
            t_str = "min"
        else:
            t_str = "mins"
        str += "{0} {1}".format(minutes, t_str)
        return str
    elif seconds > 0:
        if seconds == 1:
            t_str = "sec"
        else:
            t_str = "secs"
        str += "{0} {1}".format(seconds, t_str)
        return str
    else:
        return str
136362
def humanize_duration(duration):
    
    days = duration.days
    hours = int(duration.seconds / 3600)
    minutes = int(duration.seconds % 3600 / 60)
    seconds = int(duration.seconds % 3600 % 60)

    parts = []
    if days > 0:
        parts.append(u'%s %s' % (days, pluralize(days, _('day,days'))))

    if hours > 0:
        parts.append(u'%s %s' % (hours, pluralize(hours, _('hour,hours'))))

    if minutes > 0:
        parts.append(u'%s %s' % (minutes, pluralize(minutes, _('minute,minutes'))))

    if seconds > 0:
        parts.append(u'%s %s' % (seconds, pluralize(seconds, _('second,seconds'))))

    return ', '.join(parts) if len(parts) != 0 else _('< 1 second')
42822
def field_timedelta_from_json(self, json_val):
        
        if isinstance(json_val, str):
            return timedelta(seconds=float(json_val))
        elif json_val is None:
            return None
        else:
            return timedelta(seconds=json_val)
770502
def duration_to_string(duration):
    

    m, s = divmod(duration, 60)
    h, m = divmod(m, 60)
    return "%d:%02d:%02d" % (h, m, s)
577013
def serialize_duration(attr, **kwargs):
        
        if isinstance(attr, str):
            attr = isodate.parse_duration(attr)
        return isodate.duration_isoformat(attr)