Converts a duration to a string

    Args:
        duration (int): The duration in seconds to convert

    Returns s (str): The duration as a string
770502
def duration_to_string(duration):
    

    m, s = divmod(duration, 60)
    h, m = divmod(m, 60)
    return "%d:%02d:%02d" % (h, m, s)
186781
def duration_to_timedelta(obj):
    
    matches = DURATION_PATTERN.search(obj)
    matches = matches.groupdict(default="0")
    matches = {k: int(v) for k, v in matches.items()}
    return timedelta(**matches)
766216
def time_str_to_minutes(time_str):
    
    time_arr = time_str.split(":")
    hours = int(time_arr[0])
    minutes = int(time_arr[1])
    return hours * 60 + minutes
81301
def parse_duration(value: StrIntFloat) -> timedelta:
    
    if isinstance(value, timedelta):
        return value

    if isinstance(value, (int, float)):
        # bellow code requires a string
        value = str(value)

    match = standard_duration_re.match(value) or iso8601_duration_re.match(value)
    if not match:
        raise errors.DurationError()

    kw = match.groupdict()
    sign = -1 if kw.pop('sign', '+') == '-' else 1
    if kw.get('microseconds'):
        kw['microseconds'] = kw['microseconds'].ljust(6, '0')

    if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):
        kw['microseconds'] = '-' + kw['microseconds']

    kw_ = {k: float(v) for k, v in kw.items() if v is not None}

    return sign * timedelta(**kw_)
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
31936
def seconds2str(seconds):
    """"""

    if seconds < 0:
        return "{0:.3g}s".format(seconds)
    elif math.isnan(seconds):
        return "NaN"
    elif math.isinf(seconds):
        return "Inf"

    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    if h >= 1:
        return "{0:g}h {1:02g}m {2:.3g}s".format(h, m, s)
    elif m >= 1:
        return "{0:02g}m {1:.3g}s".format(m, s)
    else:
        return "{0:.3g}s".format(s)
1154196
def timedelta_to_duration(obj):
    
    minutes, hours, days = 0, 0, 0
    seconds = int(obj.total_seconds())
    if seconds > 59:
        minutes = seconds // 60
        seconds = seconds % 60
    if minutes > 59:
        hours = minutes // 60
        minutes = minutes % 60
    if hours > 23:
        days = hours // 24
        hours = hours % 24
    response = []
    if days:
        response.append('%sd' % days)
    if hours:
        response.append('%sh' % hours)
    if minutes:
        response.append('%sm' % minutes)
    if seconds or not response:
        response.append('%ss' % seconds)
    return "".join(response)
929268
static public String convertStringFromDuration(
            Duration duration, DurationConverterSettings settings) {
        if ((duration == null) || (duration.isNegative())) {
            return "";
        }
        long seconds = duration.getSeconds();

        HashSet<DurationUnit> usedUnits
                = getUsedDurationUnitSet(settings.smallestUsedUnit, settings.largestUsedUnit);
        if (usedUnits.isEmpty()) {
            throw new RuntimeException("convertStringFromDuration(), The \"used duration unit\" "
                    + "variables do not allow any units to be used.");
        }
        boolean hasNoNanos = (duration.getNano() == 0);

        DurationUnit smallestUnit = settings.smallestUsedUnit;
        HashMap<DurationUnit, String> unitsSingular = settings.translationsUnitsSingular;
        HashMap<DurationUnit, String> unitsPlural = settings.translationsUnitsPlural;
        HashMap<DurationUnit, Boolean> pluralRules = settings.pluralUnitsMap;
        int oneYear = DurationUnit.Year.inSeconds;
        int oneMonth = DurationUnit.Month.inSeconds;
        int oneWeek = DurationUnit.Week.inSeconds;
        int oneDay = DurationUnit.Day.inSeconds;
        int oneHour = DurationUnit.Hour.inSeconds;
        int oneMinute = DurationUnit.Minute.inSeconds;
        int thirtyMinutes = DurationUnit.Second.thirtyMinutesInSeconds;

        String result = "";
        long value;
        boolean yearIsBestChoice = usedUnits.contains(DurationUnit.Year) && hasNoNanos
                && (seconds >= oneYear) && (seconds % oneYear == 0);
        if (yearIsBestChoice || (DurationUnit.Year == smallestUnit)) {
            value = seconds / oneYear;
            result += value + " ";
            result += ((pluralRules.get(DurationUnit.Year) && (value != 1))
                    ? unitsPlural.get(DurationUnit.Year) : unitsSingular.get(DurationUnit.Year));
            return result;
        }
        boolean monthIsBestChoice = usedUnits.contains(DurationUnit.Month) && hasNoNanos
                && (seconds >= oneMonth) && (seconds % oneMonth == 0);
        if (monthIsBestChoice || (DurationUnit.Month == smallestUnit)) {
            value = seconds / oneMonth;
            result += value + " ";
            result += ((pluralRules.get(DurationUnit.Month) && (value != 1))
                    ? unitsPlural.get(DurationUnit.Month) : unitsSingular.get(DurationUnit.Month));
            return result;
        }
        boolean weekIsBestChoice = usedUnits.contains(DurationUnit.Week) && hasNoNanos
                && (seconds >= oneWeek) && (seconds % oneWeek == 0);
        if (weekIsBestChoice || (DurationUnit.Week == smallestUnit)) {
            value = seconds / oneWeek;
            result += value + " ";
            result += ((pluralRules.get(DurationUnit.Week) && (value != 1))
                    ? unitsPlural.get(DurationUnit.Week) : unitsSingular.get(DurationUnit.Week));
            return result;
        }
        boolean dayIsBestChoice = usedUnits.contains(DurationUnit.Day) && hasNoNanos
                && (seconds >= oneDay) && (seconds % oneDay == 0);
        if (dayIsBestChoice || (DurationUnit.Day == smallestUnit)) {
            value = seconds / oneDay;
            result += value + " ";
            result += ((pluralRules.get(DurationUnit.Day) && (value != 1))
                    ? unitsPlural.get(DurationUnit.Day) : unitsSingular.get(DurationUnit.Day));
            return result;
        }

        boolean hourDecimalIsBestChoice = settings.hoursCanUseThirtyMinuteDecimals
                && usedUnits.contains(DurationUnit.Hour) && hasNoNanos
                && (seconds >= oneHour) && (seconds <= settings.hoursMaximumValueForDecimalsInSeconds)
                && (seconds % thirtyMinutes == 0) && (seconds % oneHour != 0);
        // Note, hourDecimal is never forced to be used as the "smallest used unit".
        if (hourDecimalIsBestChoice) {
            value = seconds / oneHour;
            // The full value is always "X.5" hour(s), due to the hourDecimalIsBestChoice criteria. 
            String decimalString = ".5";
            result += value + decimalString + " ";
            result += ((pluralRules.get(DurationUnit.Hour))
                    ? unitsPlural.get(DurationUnit.Hour) : unitsSingular.get(DurationUnit.Hour));
            return result;
        }

        boolean hourIntegerIsBestChoice = usedUnits.contains(DurationUnit.Hour) && hasNoNanos
                && (seconds >= oneHour) && (seconds % oneHour == 0);
        if (hourIntegerIsBestChoice || (DurationUnit.Hour == smallestUnit)) {
            value = seconds / oneHour;
            result += value + " ";
            result += ((pluralRules.get(DurationUnit.Hour) && (value != 1))
                    ? unitsPlural.get(DurationUnit.Hour) : unitsSingular.get(DurationUnit.Hour));
            return result;
        }

        boolean minuteIsBestChoice = usedUnits.contains(DurationUnit.Minute) && hasNoNanos
                && (seconds >= oneMinute) && (seconds % oneMinute == 0);
        if (minuteIsBestChoice || (DurationUnit.Minute == smallestUnit)) {
            value = seconds / oneMinute;
            result += value + " ";
            result += ((pluralRules.get(DurationUnit.Minute) && (value != 1))
                    ? unitsPlural.get(DurationUnit.Minute) : unitsSingular.get(DurationUnit.Minute));
            return result;
        }

        boolean secondIsBestChoice = usedUnits.contains(DurationUnit.Second);
        if (secondIsBestChoice || (DurationUnit.Second == smallestUnit)) {
            value = seconds;
            int nanosecondsFromDuration = duration.getNano();
            boolean includeNanoseconds = (nanosecondsFromDuration != 0);
            BigDecimal nanosecondsInSeconds = BigDecimal.valueOf(nanosecondsFromDuration, 9);
            BigDecimal secondsWithNanosAdded = nanosecondsInSeconds.add(new BigDecimal(value));
            secondsWithNanosAdded = secondsWithNanosAdded.stripTrailingZeros();
            result += ((includeNanoseconds) ? secondsWithNanosAdded.toPlainString() : value);
            result += " ";
            result += (pluralRules.get(DurationUnit.Second) && ((value != 1) || (includeNanoseconds)))
                    ? unitsPlural.get(DurationUnit.Second) : unitsSingular.get(DurationUnit.Second);
            return result;
        }
        throw new RuntimeException("convertStringFromDuration(), "
                + "The duration unit could not be chosen. (This should not happen.)");
    }
148711
def timedelta_to_duration(dt):
    
    days, secs = dt.days, dt.seconds
    res = 'P'
    if days // 7:
        res += str(days // 7) + 'W'
        days %= 7
    if days:
        res += str(days) + 'D'
    if secs:
        res += 'T'
        if secs // 3600:
            res += str(secs // 3600) + 'H'
            secs %= 3600
        if secs // 60:
            res += str(secs // 60) + 'M'
            secs %= 60
        if secs:
            res += str(secs) + 'S'
    return res
864427
def parse_duration(string):
    
    if string.isdigit():
        return int(string)
    try:
        return float(string)
    except ValueError:
        pass
    string = string.rstrip()
    for (suf, mult) in DURATION_SUFFIX_MAP.items():
        if string.lower().endswith(suf):
            try:
                return parse_duration(string[:-len(suf)].strip()) * mult
            except TypeError:
                return
1035730
def str(self,local):
        
        s = self.start_time.str(local) \
            + u" to " \
            + self.end_time.str(local)
        return s
620438
@NonNull
    public static String convertDuration(@IntRange(from = 1) long duration) {
        duration /= 1000;
        int hour = (int) (duration / 3600);
        int minute = (int) ((duration - hour * 3600) / 60);
        int second = (int) (duration - hour * 3600 - minute * 60);

        String hourValue = "";
        String minuteValue;
        String secondValue;
        if (hour > 0) {
            if (hour >= 10) {
                hourValue = Integer.toString(hour);
            } else {
                hourValue = "0" + hour;
            }
            hourValue += ":";
        }
        if (minute > 0) {
            if (minute >= 10) {
                minuteValue = Integer.toString(minute);
            } else {
                minuteValue = "0" + minute;
            }
        } else {
            minuteValue = "00";
        }
        minuteValue += ":";
        if (second > 0) {
            if (second >= 10) {
                secondValue = Integer.toString(second);
            } else {
                secondValue = "0" + second;
            }
        } else {
            secondValue = "00";
        }
        return hourValue + minuteValue + secondValue;
    }
693266
public static Duration of(String duration) {
    Matcher matcher = PATTERN.matcher(duration);
    Assert.arg(matcher.matches(), "Invalid duration: %s", duration);

    if (matcher.group(1) != null) {
      return Duration.ofSeconds(Long.MAX_VALUE);
    } else {
      String unit = matcher.group(4);
      String value = matcher.group(3);
      return Duration.ofNanos(TimeUnit.NANOSECONDS.convert(Long.parseLong(value),
          unit == null ? TimeUnit.MILLISECONDS : SUFFIXES.get(unit)));
    }
  }
1002239
def to_long_time_string(self) -> str:
        
        hour = self.time.hour
        minute = self.time.minute
        second = self.time.second
        return f"{hour:02}:{minute:02}:{second:02}"
633844
public static StringBuilder durationConfigString(Duration duration) {
        Duration remainder = duration;

        long days = remainder.getStandardDays();
        remainder = remainder.minus(Duration.standardDays(days));

        long hours = remainder.getStandardHours();
        remainder = remainder.minus(Duration.standardHours(hours));

        long minutes = remainder.getStandardMinutes();
        remainder = remainder.minus(Duration.standardMinutes(minutes));

        long seconds = remainder.getStandardSeconds();
        remainder = remainder.minus(Duration.standardSeconds(seconds));

        if (!remainder.isEqual(Duration.ZERO))
            Logger.getLogger(ConfigSupport.class.getName()).log(Level.WARNING, "Duration is more precise than configuration will handle: {0}, dropping remainder: {1}", new Object[]{duration, remainder});

        StringBuilder result = new StringBuilder();
        if (days != 0) {
            if (result.length() != 0) result.append(' ');
            result.append(days).append('d');
        }
        if (hours != 0) {
            if (result.length() != 0) result.append(' ');
            result.append(hours).append('h');
        }
        if (minutes != 0) {
            if (result.length() != 0) result.append(' ');
            result.append(minutes).append('m');
        }
        if (result.length() == 0 || seconds != 0) {
            if (result.length() != 0) result.append(' ');
            result.append(seconds).append('s');
        }

        return result;
    }
819376
public String format(Duration duration) {
    Long durationInMinutes = duration.toMinutes();
    if (durationInMinutes == 0) {
      return "0";
    }
    boolean isNegative = durationInMinutes < 0;
    Long absDuration = Math.abs(durationInMinutes);

    int days = ((Double) ((double) absDuration / HOURS_IN_DAY / 60)).intValue();
    Long remainingDuration = absDuration - (days * HOURS_IN_DAY * 60);
    int hours = ((Double) (remainingDuration.doubleValue() / 60)).intValue();
    remainingDuration = remainingDuration - (hours * 60);
    int minutes = remainingDuration.intValue();

    return format(days, hours, minutes, isNegative);
  }
506515
def toStringDuration (duration):
    

    table = (
        ('%dms'      , 1e-3, 1e3),
        (u'%d\u03BCs', 1e-6, 1e6),
        ('%dns'      , 1e-9, 1e9)
    )

    if duration > 1:
        return '%fs' % duration

    for format, threshold, factor in table:
        if duration > threshold:
            return format % int(duration * factor)

    return '%fs' % duration