@method convertISO8601DurationToMilliseconds
@static
@param {String} ISO8601Duration Duration in ISO8601 format
@return {Int} Duration in milliseconds

Note: does not handle input strings with years, months and days
354955
function (ISO8601Duration) {
            var isValueNegative = (ISO8601Duration.indexOf("-") >= 0),
                indexOfT = ISO8601Duration.indexOf("T"),
                indexOfH = ISO8601Duration.indexOf("H"),
                indexOfM = ISO8601Duration.indexOf("M"),
                indexOfS = ISO8601Duration.indexOf("S"),
                hours,
                minutes,
                seconds,
                durationInMilliseconds;

            if ((indexOfT === -1) || ((indexOfM !== -1) && (indexOfM < indexOfT)) || (ISO8601Duration.indexOf("D") !== -1) || (ISO8601Duration.indexOf("Y") !== -1)) {
                throw new Error("ISO 8601 timestamps including years, months and/or days are not currently supported");
            }

            if (indexOfH === -1) {
                indexOfH = indexOfT;
                hours = 0;
            }
            else {
                hours = parseInt(ISO8601Duration.slice(indexOfT + 1, indexOfH), 10);
            }

            if (indexOfM === -1) {
                indexOfM = indexOfT;
                minutes = 0;
            }
            else {
                minutes = parseInt(ISO8601Duration.slice(indexOfH + 1, indexOfM), 10);
            }

            seconds = parseFloat(ISO8601Duration.slice(indexOfM + 1, indexOfS));

            durationInMilliseconds = parseInt((((((hours * 60) + minutes) * 60) + seconds) * 1000), 10);
            if (isNaN(durationInMilliseconds)){
                durationInMilliseconds = 0;
            }
            if (isValueNegative) {
                durationInMilliseconds = durationInMilliseconds * -1;
            }

            return durationInMilliseconds;
        }
1155982
def parse_iso8601_datetime(string):
    

    # Match ISO 8601?
    match = _RE_ISO8601_DATETIME.search(string)
    if not match:
        raise ValueError('Expected ISO 8601 date/time')

    # Extract ISO 8601 components
    year = int(match.group('year'))
    month = int(match.group('month'))
    day = int(match.group('day'))
    hour = int(match.group('hour')) if match.group('hour') else 0
    minute = int(match.group('min')) if match.group('min') else 0
    sec = int(match.group('sec')) if match.group('sec') else 0
    microsec = int(float('.' + match.group('fracsec')) * 1000000) if match.group('fracsec') else 0
    offhour = int(match.group('offsign') + match.group('offhour')) if match.group('offhour') else 0
    offmin = int(match.group('offsign') + match.group('offmin')) if match.group('offmin') else 0

    return (datetime(year, month, day, hour, minute, sec, microsec, TZUTC) -
            timedelta(hours=offhour, minutes=offmin))
1243931
def from_iso8601(s):
    
    m = _iso8601_fmt.match(s)
    if not m:
        m = _iso8601_fmt_date.match(s)

    if not m:
        raise ValueError('not a valid iso 8601 format string:[{0}]'.format(s))

    g = m.groupdict()

    def _default_zero(key):
        v = g.get(key, None)
        return int(v) if v else 0

    def _default_none(key):
        v = g.get(key, None)
        return int(v) if v else None

    year = _default_zero('year')
    month = _default_zero('month')
    day = _default_zero('day')
    hour = _default_none('hour')
    minute = _default_none('minute')
    second = _default_none('second')
    microsecond = g.get('microsecond', None)
    if microsecond is not None:
        # append zero when not matching 6 digits
        microsecond = int(microsecond + '0' * (6 - len(microsecond)))
    tz_s = g.get('tz')

    if not (year and month and day):
        raise ValueError('missing y-m-d: [{0}]'.format(s))

    # only date part, time part is none
    if hour == None and minute == None and second == None:
        return datetime.datetime(year, month, day)

    # prepare tz info
    tz = None
    if tz_s:
        if hour is None and minute is None:
            raise ValueError('missing h:m when tzinfo is provided: [{0}]'.format(s))

        negtive = hh = mm = 0

        if tz_s != 'Z':
            negtive = -1 if tz_s[0] == '-' else 1
            hh = int(tz_s[1:3])
            mm = int(tz_s[4:6]) if len(tz_s) > 5 else 0

        tz = FixedTZ(h=hh*negtive, m=mm*negtive)

    return datetime.datetime(
        year=year,
        month=month,
        day=day,
        hour=hour or 0,
        minute=minute or 0,
        second=second or 0,
        microsecond=microsecond or 0,
        tzinfo=tz
    )
886443
def to_iso8601(value, strict=True, force_int=True):
    
    # split seconds to larger units
    # seconds = value.total_seconds()
    seconds = to_seconds(value, strict, force_int)

    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
    days, hours, minutes = map(int, (days, hours, minutes))
    seconds = round(seconds, 6)

    # build date
    date = ''
    if days:
        date = '%sD' % days

    # build time
    time = 'T'

    # hours
    bigger_exists = date or hours
    if bigger_exists:
        time += '{:02}H'.format(hours)

    # minutes
    bigger_exists = bigger_exists or minutes
    if bigger_exists:
        time += '{:02}M'.format(minutes)

    # seconds
    if isinstance(seconds, int) or force_int:
        seconds = '{:02}'.format(int(seconds))
    else:
        # 9 chars long w/leading 0, 6 digits after decimal
        seconds = '%09.6f' % seconds

    time += '{}S'.format(seconds)
    return 'P' + date + time
1113054
def fromISO(cls, iso_string):

        ''' 
        '''

    # validate input
        title = 'ISO time input for labDT.fromISO'
        isopattern = re.compile('\d{4}-?\d{2}-?\d{2}[\s|T].*')
        if not isopattern.search(iso_string):
            raise ValueError('\n%s is not a valid ISO string.' % title)
        python_datetime = dTparser.parse(iso_string)
        if not python_datetime.tzinfo:
            raise ValueError('\n%s must have timezone info.' % title)

    # construct labDT from parsed string
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)
545996
function basicISODate(date) {
		// Can be done with `str.replace(/(-|:|\.\d{3}Z$)/g, '')`, but `substr()` performs better: http://jsperf.com/iso8601-date-basic-format
		var str = (date || new Date()).toISOString();
		return str.substr(0, 4) + str.substr(5, 2) + str.substr(8, 5) + str.substr(14, 2) + str.substr(17, 2) + 'Z';
	}
536092
function timeElapsed(timeStamp) {
		var diff = _timeDifference(timeStamp);
		var yearStr = _generateTimeString(diff.year, "a year", "years");
		var monthStr = _generateTimeString(diff.month, "a month", "months");
		var dayStr = _generateTimeString(diff.day, "a day", "days");
		var hourStr = _generateTimeString(diff.hour, "an hour", "hours");
		var minuteStr = _generateTimeString(diff.minute, "a minute", "minutes");
		var disPlayStr = "";
		if(yearStr) {
			disPlayStr = diff.year > 0 ? yearStr : yearStr + monthStr;
		} else if(monthStr) {
			disPlayStr = diff.month > 0 ? monthStr : monthStr + dayStr;
		} else if(dayStr) {
			disPlayStr = diff.day > 0 ? dayStr : dayStr + hourStr;
		} else if(hourStr) {
			disPlayStr = diff.hour > 0 ? hourStr : hourStr + minuteStr;
		} else if(minuteStr) {
			disPlayStr = minuteStr;
		}
		return disPlayStr;	
	}
449776
public long getDurationMillis(Object object) {
        // parse here because duration could be bigger than the int supported
        // by the period parser
        String original = (String) object;
        String str = original;
        int len = str.length();
        if (len >= 4 &&
            (str.charAt(0) == 'P' || str.charAt(0) == 'p') &&
            (str.charAt(1) == 'T' || str.charAt(1) == 't') &&
            (str.charAt(len - 1) == 'S' || str.charAt(len - 1) == 's')) {
            // ok
        } else {
            throw new IllegalArgumentException("Invalid format: \"" + original + '"');
        }
        str = str.substring(2, len - 1);
        int dot = -1;
        boolean negative = false;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                // ok
            } else if (i == 0 && str.charAt(0) == '-') {
                // ok
                negative = true;
            } else if (i > (negative ? 1 : 0) && str.charAt(i) == '.' && dot == -1) {
                // ok
                dot = i;
            } else {
                throw new IllegalArgumentException("Invalid format: \"" + original + '"');
            }
        }
        long millis = 0, seconds = 0;
        int firstDigit = negative ? 1 : 0;
        if (dot > 0) {
            seconds = Long.parseLong(str.substring(firstDigit, dot));
            str = str.substring(dot + 1);
            if (str.length() != 3) {
                str = (str + "000").substring(0, 3);
            }
            millis = Integer.parseInt(str);
        } else if (negative) {
            seconds = Long.parseLong(str.substring(firstDigit, str.length()));
        } else {
            seconds = Long.parseLong(str);
        }
        if (negative) {
            return FieldUtils.safeAdd(FieldUtils.safeMultiply(-seconds, 1000), -millis);
        } else {
            return FieldUtils.safeAdd(FieldUtils.safeMultiply(seconds, 1000), millis);
        }
    }
709356
function convertTimestampToBigEndian(timestamp) {
  // The timestamp parameter in Big-Endian UInt-64 format
  var buffer = new Buffer(8);
  buffer.fill(0);

  var high = ~~(timestamp / 0xffffffff); // jshint ignore:line
  var low = timestamp % (0xffffffff + 0x1); // jshint ignore:line

  buffer.writeUInt32BE(parseInt(high, 10), 0);
  buffer.writeUInt32BE(parseInt(low, 10), 4);

  return buffer;
}
637056
function timeInMs(time) {
	var HOUR_IN_MS = 3.6e+6,
		DAY_IN_MS = HOUR_IN_MS * 24,
		WK_IN_MS = DAY_IN_MS * 7,
		MS_DICTIONARY = {
			'weeks': WK_IN_MS,
			'week': WK_IN_MS,
			'w': WK_IN_MS,
			'days': DAY_IN_MS,
			'day': DAY_IN_MS,
			'd': DAY_IN_MS,
			'hours': HOUR_IN_MS,
			'hour': HOUR_IN_MS,
			'h': HOUR_IN_MS
		};

	var duration = parseInt(time, 10);
	var interval = time.replace(/\d*[\d]/, '').trim();

	if (Object.keys(MS_DICTIONARY).indexOf(interval) < 0) {
		throw new Error('Interval is invalid. The ttl must be of weeks, days, or hours');
	}

	return MS_DICTIONARY[interval] * duration;
}
1290172
function parseISO(config) {
        var i, l,
            string = config._i,
            match = isoRegex.exec(string);

        if (match) {
            config._pf.iso = true;
            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(string)) {
                    // match[5] should be "T" or undefined
                    config._f = isoDates[i][0] + (match[6] || " ");
                    break;
                }
            }
            for (i = 0, l = isoTimes.length; i < l; i++) {
                if (isoTimes[i][1].exec(string)) {
                    config._f += isoTimes[i][0];
                    break;
                }
            }
            if (string.match(parseTokenTimezone)) {
                config._f += "Z";
            }
            makeDateFromStringAndFormat(config);
        } else {
            config._isValid = false;
        }
    }
506987
def pretty_duration(seconds):
    
    if seconds is None:
        return ''
    ret = ''
    if seconds >= 86400:
        ret += '{:.0f}d'.format(int(seconds / 86400))
        seconds = seconds % 86400
    if seconds >= 3600:
        ret += '{:.0f}h'.format(int(seconds / 3600))
        seconds = seconds % 3600
    if seconds >= 60:
        ret += '{:.0f}m'.format(int(seconds / 60))
        seconds = seconds % 60
    if seconds > 0:
        ret += '{:.1f}s'.format(seconds)
    return ret
1326584
function getElapsedTimeString(startTimestampMs, updatedTimestampMs) {
  var updatedDiff = Math.max(0, updatedTimestampMs - startTimestampMs);
  var updatedDays = Math.floor(updatedDiff / 86400000.0);
  updatedDiff -= (updatedDays * 86400000.0);
  var updatedHours = Math.floor(updatedDiff / 3600000.0);
  updatedDiff -= (updatedHours * 3600000.0);
  var updatedMinutes = Math.floor(updatedDiff / 60000.0);
  updatedDiff -= (updatedMinutes * 60000.0);
  var updatedSeconds = Math.floor(updatedDiff / 1000.0);
  updatedDiff -= (updatedSeconds * 1000.0);
  var updatedMs = Math.floor(updatedDiff / 1.0);

  var updatedString = '';

  if (updatedMinutes > 0) {
    if (updatedDays == 1) {
      updatedString = '1 day, ';
    } else if (updatedDays > 1) {
      updatedString = '' + updatedDays + ' days, ';
    }
    updatedString +=
        leftPadNumber(updatedHours, 2, '0') + ':' +
        leftPadNumber(updatedMinutes, 2, '0') + ':' +
        leftPadNumber(updatedSeconds, 2, '0');
    if (updatedMs > 0) {
      updatedString += '.' + leftPadNumber(updatedMs, 3, '0');
    }
  } else {
    updatedString += updatedSeconds;
    updatedString += '.' + leftPadNumber(updatedMs, 3, '0');
    updatedString += ' seconds';
  }

  return updatedString;
}
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
183207
function(isoString, pointSpan) {
            var i18n = Splunk.JSCharting.i18nUtils,
                bdTime = this.extractBdTime(isoString),
                dateObject;

            if(bdTime.isInvalid) {
                return null;
            }
            dateObject = this.bdTimeToDateObject(bdTime);

            if (pointSpan >= this.MIN_SECS_PER_DAY) { // day or larger
                return i18n.format_date(dateObject);
            }
            else if (pointSpan >= this.SECS_PER_MIN) { // minute or longer
                return format_datetime(dateObject, 'medium', 'short');
            }
            return format_datetime(dateObject);
        }
1356143
function toLocalIsoString(date, includeMillis) {
    if (includeMillis === undefined) {
        includeMillis = false;
    }
    const pad = (n, length, padChar) => {
        if (length === undefined) { length = 2; }
        if (padChar === undefined) { padChar = "0"; }
        let str = "" + n;
        while (str.length < length) {
            str = padChar + str;
        }
        return str;
    };
    const getOffsetFromUTC = () => {
        const offset = date.getTimezoneOffset();
        if (offset === 0) {
            return "Z";
        }
        return (offset < 0 ? "+" : "-")
            + pad(Math.abs(offset / 60), 2) + ":"
            + pad(Math.abs(offset % 60), 2);
    };
    return date.getFullYear() + "-"
        + pad(date.getMonth() + 1) + "-"
        + pad(date.getDate()) + "T"
        + pad(date.getHours()) + ":"
        + pad(date.getMinutes()) + ":"
        + pad(date.getSeconds())
        + (includeMillis ? "." + pad(date.getMilliseconds(), 3) : "")
        + getOffsetFromUTC();
}
396777
def convert_durations(metric):
    
    if metric[0] == 'avgSessionDuration' and metric[1]:
        new_metric = (metric[0], metric[1] * 1000)
    else:
        new_metric = metric
    return new_metric