Converts time (in milliseconds) to human-readable format
"<w> days, <x> hours, <y> minutes and (z) seconds". Milliseconds are not
taken into consideration.
437418
public static String toHuman(long duration) {
        StringBuffer res = new StringBuffer();
        long temp = 0;
        if (duration >= ONE_SECOND) {
            temp = duration / ONE_DAY;
            if (temp > 0) {
                duration -= temp * ONE_DAY;
                res.append(temp).append(" day").append(temp > 1 ? "s" : "")
                        .append(duration >= ONE_MINUTE ? ", " : "");
            }

            temp = duration / ONE_HOUR;
            if (temp > 0) {
                duration -= temp * ONE_HOUR;
                res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
                        .append(duration >= ONE_MINUTE ? ", " : "");
            }

            temp = duration / ONE_MINUTE;
            if (temp > 0) {
                duration -= temp * ONE_MINUTE;
                res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
            }

            if (!res.toString().equals("") && duration >= ONE_SECOND) {
                res.append(" and ");
            }

            temp = duration / ONE_SECOND;
            if (temp > 0) {
                res.append(temp).append(" second").append(temp > 1 ? "s" : "");
            }
            return res.toString();
        } else {
            return "0 second";
        }
    }
307112
def CopyToDateTimeString(self):
    
    if self._number_of_seconds is None:
      return None

    return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format(
        self._time_elements_tuple[0], self._time_elements_tuple[1],
        self._time_elements_tuple[2], self._time_elements_tuple[3],
        self._time_elements_tuple[4], self._time_elements_tuple[5])
460832
def humantime(time):
    
    try:
        time = float(time)
    except (ValueError, TypeError):
        raise ValueError("Input must be numeric")

    # weeks
    if time >= 7 * 60 * 60 * 24:
        weeks = math.floor(time / (7 * 60 * 60 * 24))
        timestr = "{:g} weeks, ".format(weeks) + humantime(time % (7 * 60 * 60 * 24))

    # days
    elif time >= 60 * 60 * 24:
        days = math.floor(time / (60 * 60 * 24))
        timestr = "{:g} days, ".format(days) + humantime(time % (60 * 60 * 24))

    # hours
    elif time >= 60 * 60:
        hours = math.floor(time / (60 * 60))
        timestr = "{:g} hours, ".format(hours) + humantime(time % (60 * 60))

    # minutes
    elif time >= 60:
        minutes = math.floor(time / 60.)
        timestr = "{:g} min., ".format(minutes) + humantime(time % 60)

    # seconds
    elif (time >= 1) | (time == 0):
        timestr = "{:g} s".format(time)

    # milliseconds
    elif time >= 1e-3:
        timestr = "{:g} ms".format(time * 1e3)

    # microseconds
    elif time >= 1e-6:
        timestr = "{:g} \u03BCs".format(time * 1e6)

    # nanoseconds or smaller
    else:
        timestr = "{:g} ns".format(time * 1e9)

    return timestr
416318
public static String formatTimeSec(long time) {

        StringBuffer str = new StringBuffer();

        if (time < 60) {
            str.append(time + " sec");
            return str.toString();
        }

        int days = (int) time / 86400;

        if (days != 0) {
            str.append(days + " days");
            time -= days * 86400;
        }

        int hours = (int) time / 3600;

        if (hours != 0) {
            if (str.length() != 0) str.append(", ");
            str.append(hours + " h");
            time -= hours * 3600;
        }

        int mins  = (int) time / 60;

        if (mins != 0) {
            if (str.length() != 0) str.append(", ");
            str.append(mins + " min");
            time -= mins * 60;
        }

        int sec   = (int) time;

        if (sec != 0) {
            if (str.length() != 0) str.append(", ");
            str.append(sec + " sec");
        }

        return str.toString();
    }
1351263
public String formatTimeInterval(final long milliseconds) {
		long curMilliseconds = milliseconds;
		final StringBuilder sb = new StringBuilder().append("PT");
		final long hours = TimeUnit.MILLISECONDS.toHours(curMilliseconds);
		if (hours < 10)
			sb.append('0');
		sb.append(hours).append('H');
		curMilliseconds -= TimeUnit.HOURS.toMillis(hours);

		final long minutes = TimeUnit.MILLISECONDS.toMinutes(curMilliseconds);
		if (minutes < 10)
			sb.append('0');
		sb.append(minutes).append('M');
		curMilliseconds -= TimeUnit.MINUTES.toMillis(minutes);

		final long seconds = TimeUnit.MILLISECONDS.toSeconds(curMilliseconds);
		if (seconds < 10)
			sb.append('0');
		sb.append(seconds);
		curMilliseconds -= TimeUnit.SECONDS.toMillis(seconds);

		if (curMilliseconds > 0)
			sb.append('.').append(curMilliseconds);

		sb.append('S');
		return sb.toString();
	}
343474
def readable_time_delta(seconds):
    
    days = seconds // 86400
    seconds -= days * 86400
    hours = seconds // 3600
    seconds -= hours * 3600
    minutes = seconds // 60

    m_suffix = 's' if minutes != 1 else ''
    h_suffix = 's' if hours != 1 else ''
    d_suffix = 's' if days != 1 else ''

    retval = u'{0} minute{1}'.format(minutes, m_suffix)

    if hours != 0:
        retval = u'{0} hour{1} and {2}'.format(hours, h_suffix, retval)

    if days != 0:
        retval = u'{0} day{1}, {2}'.format(days, d_suffix, retval)

    return retval
860936
def humanize_seconds(total_seconds,
                     frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
                     negative_frmt=None):
    
    if negative_frmt is None:
        negative_frmt = '<span class="negative-time">-{0}</span>'.format(frmt)
    seconds = abs(int(total_seconds))
    mapping = {
        'hours': seconds // 3600,
        'minutes': seconds % 3600 // 60,
        'seconds': seconds % 3600 % 60,
    }
    if total_seconds < 0:
        result = negative_frmt.format(**mapping)
    else:
        result = frmt.format(**mapping)
    return mark_safe(result)
457365
def get_readable_time_string(seconds):
    """"""
    seconds = int(seconds)
    minutes = seconds // 60
    seconds = seconds % 60
    hours = minutes // 60
    minutes = minutes % 60
    days = hours // 24
    hours = hours % 24

    result = ""
    if days > 0:
        result += "%d %s " % (days, "Day" if (days == 1) else "Days")
    if hours > 0:
        result += "%d %s " % (hours, "Hour" if (hours == 1) else "Hours")
    if minutes > 0:
        result += "%d %s " % (minutes, "Minute" if (minutes == 1) else "Minutes")
    if seconds > 0:
        result += "%d %s " % (seconds, "Second" if (seconds == 1) else "Seconds")

    return result.strip()
378013
def format_time(time_string):
    '''
    
    '''
    subseconds = False
    data = time_string.split("_")
    hours, minutes, seconds = int(data[3]), int(data[4]), int(data[5])
    date = datetime.datetime.strptime("_".join(data[:3]), "%Y_%m_%d")
    subsec = 0.0
    if len(data) == 7:
        if float(data[6]) != 0:
            subsec = float(data[6]) / 10**len(data[6])
            subseconds = True
    date_time = date + \
        datetime.timedelta(hours=hours, minutes=minutes,
                           seconds=seconds + subsec)
    return date_time, subseconds
783216
def to_timedelta(value):
    """"""
    if value is None:
        return None
    if isinstance(value, (six.integer_types, float)):
        return timedelta(microseconds=(float(value) / 10))
    match = _TIMESPAN_PATTERN.match(value)
    if match:
        if match.group(1) == "-":
            factor = -1
        else:
            factor = 1
        return factor * timedelta(
            days=int(match.group("d") or 0),
            hours=int(match.group("h")),
            minutes=int(match.group("m")),
            seconds=float(match.group("s")),
        )
    else:
        raise ValueError("Timespan value '{}' cannot be decoded".format(value))
543132
def CopyToDateTimeString(self):
    
    if self._timestamp is None:
      return None

    number_of_days, hours, minutes, seconds = self._GetTimeValues(
        int(self._timestamp))

    year, month, day_of_month = self._GetDateValuesWithEpoch(
        number_of_days, self._EPOCH)

    microseconds = int(
        (self._timestamp % 1) * definitions.MICROSECONDS_PER_SECOND)

    return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'.format(
        year, month, day_of_month, hours, minutes, seconds, microseconds)
997419
def formatTime(self, record, datefmt=None):
        """"""
        _seconds_fraction = record.created - int(record.created)
        _datetime_utc = time.mktime(time.gmtime(record.created))
        _datetime_utc += _seconds_fraction
        _created = self.converter(_datetime_utc)

        if datefmt:
            time_string = _created.strftime(datefmt)
        else:
            time_string = _created.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
            time_string = "%s,%03d" % (time_string, record.msecs)
        return time_string
226419
def format_time( sec ):
    ''' 
    '''
    import time
    if sec < 864000:
       # Idea from:   http://stackoverflow.com/a/1384565
       return time.strftime('%H:%M:%S', time.gmtime(sec))
    else:
       days = int(sec / 864000)
       secs = sec % 864000
       return str(days)+'d, '+time.strftime('%H:%M:%S', time.gmtime(secs))
637196
def humanize_timedelta(seconds):
    """"""
    hours, remainder = divmod(seconds, 3600)
    days, hours = divmod(hours, 24)
    minutes, seconds = divmod(remainder, 60)

    if days:
        result = '{}d'.format(days)
        if hours:
            result += ' {}h'.format(hours)
        if minutes:
            result += ' {}m'.format(minutes)
        return result

    if hours:
        result = '{}h'.format(hours)
        if minutes:
            result += ' {}m'.format(minutes)
        return result

    if minutes:
        result = '{}m'.format(minutes)
        if seconds:
            result += ' {}s'.format(seconds)
        return result

    return '{}s'.format(seconds)
1369444
public static String datetime(long millis) {
		if (sFormat == null) {
			sFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("UTC"),
					US);
		}
		return sFormat.format(millis);
	}
252075
def ms_to_timestamp(ms):
    """'"""
    # XXX throw on overflow/underflow?
    if ms < 0: ms = 0
    if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME
    h, m, s, ms = ms_to_times(ms)
    return "%01d:%02d:%02d.%02d" % (h, m, s, ms//10)
1282465
function (durationInNanoSeconds) {
        // convert it to MILLI_SECONDS
        var durationInMillis = _.floor(durationInNanoSeconds / 1000000);

        var oneMilliSecond = 1000;
        var oneMinute = 60 * oneMilliSecond;
        var formattedDuration = '0s';

        function format(min, sec, ms) {
            var MINUTES = 'm ';
            var SECONDS = 's ';
            var MILLI_SECONDS = 'ms';
            var formattedTimeStamp = '';

            min > 0 ? formattedTimeStamp += min + MINUTES : '';
            sec > 0 ? formattedTimeStamp += sec + SECONDS : '';
            ms > 0 ? formattedTimeStamp += ms + MILLI_SECONDS : '';

            return formattedTimeStamp.trim().length === 0 ? '< 1ms' : formattedTimeStamp;
        }

        if (!isNaN(durationInMillis)) {

            var min = _.floor(durationInMillis / oneMinute);
            var sec = _.floor((durationInMillis % oneMinute) / oneMilliSecond);
            var ms = durationInMillis % oneMilliSecond;

            formattedDuration = format(min, sec, ms);
        }

        return formattedDuration;
    }