Given an array of timedeltas, returns a CF compatible time-unit from
    {'days', 'hours', 'minutes' 'seconds'} (the first one that can evenly
    divide all unique time deltas in `deltas`)
180297
def infer_timedelta_units(deltas):
    
    deltas = pd.to_timedelta(np.asarray(deltas).ravel(), box=False)
    unique_timedeltas = np.unique(deltas[pd.notnull(deltas)])
    units = _infer_time_units_from_diff(unique_timedeltas)
    return units
194702
def abs_timedelta(delta):
    """"""
    if delta.days < 0:
        now = _now()
        return now - (now + delta)
    return delta
805693
def format_timedelta(dt: timedelta) -> str:
    
    seconds = int(dt.total_seconds())
    days, remainder = divmod(seconds, 86400)
    hours, remainder = divmod(remainder, 3600)
    minutes, seconds = divmod(remainder, 60)
    s = ""
    if days > 0:
        s += str(days) + "d"
    if hours > 0:
        s += str(hours) + "h"
    if minutes > 0:
        s += str(minutes) + "min"
    if s == "":
        s = "0min"
    return s
901021
def decode_cf_timedelta(num_timedeltas, units):
    
    num_timedeltas = np.asarray(num_timedeltas)
    units = _netcdf_to_numpy_timeunit(units)

    shape = num_timedeltas.shape
    num_timedeltas = num_timedeltas.ravel()

    result = pd.to_timedelta(num_timedeltas, unit=units, box=False)
    # NaT is returned unboxed with wrong units; this should be fixed in pandas
    if result.dtype != 'timedelta64[ns]':
        result = result.astype('timedelta64[ns]')
    return result.reshape(shape)
242413
def sorted_timezones():
    
    def hourmin(delta):
        if delta.days < 0:
            hours, remaining = divmod(86400 - delta.seconds, 3600)
        else:
            hours, remaining = divmod(delta.seconds, 3600)
        minutes, remaining = divmod(remaining, 60)
        return hours, minutes

    now = datetime.utcnow()
    # Make a list of country code mappings
    timezone_country = {}
    for countrycode in pytz.country_timezones:
        for timezone in pytz.country_timezones[countrycode]:
            timezone_country[timezone] = countrycode

    # Make a list of timezones, discarding the US/* and Canada/* zones since they aren't reliable for
    # DST, and discarding UTC and GMT since timezones in that zone have their own names
    timezones = [(pytz.timezone(tzname).utcoffset(now, is_dst=False), tzname) for tzname in pytz.common_timezones
        if not tzname.startswith('US/') and not tzname.startswith('Canada/') and tzname not in ('GMT', 'UTC')]
    # Sort timezones by offset from UTC and their human-readable name
    presorted = [(delta, '%s%s - %s%s (%s)' % (
        (delta.days < 0 and '-') or (delta.days == 0 and delta.seconds == 0 and ' ') or '+',
        '%02d:%02d' % hourmin(delta),
        (pytz.country_names[timezone_country[name]] + ': ') if name in timezone_country else '',
        name.replace('_', ' '),
        pytz.timezone(name).tzname(now, is_dst=False)), name) for delta, name in timezones]
    presorted.sort()
    # Return a list of (timezone, label) with the timezone offset included in the label.
    return [(name, label) for (delta, label, name) in presorted]
1136665
def _times(t0, hours):
		
		if not isinstance(hours, Iterable):
			return Tide._times(t0, [hours])[0]
		elif not isinstance(hours[0], datetime):
			return np.array([t0 + timedelta(hours=h) for h in hours])
		else:
			return np.array(hours)
349567
def delta(self):
        
        number      = self._numberSpinner.value()
        unit        = self._unitCombo.currentText()
        direction   = self._directionCombo.currentText()
        
        # use past tense
        if direction == 'ago':
            number = -number
        
        if unit == 'year(s)':
            return datetime.timedelta(number * 365)
        elif unit == 'month(s)':
            return datetime.timedelta(number * 30)
        elif unit == 'week(s)':
            return datetime.timedelta(number * 7)
        elif unit == 'day(s)':
            return datetime.timedelta(number)
        elif unit == 'hour(s)':
            return datetime.timedelta(0, number * 3600)
        elif unit == 'minute(s)':
            return datetime.timedelta(0, number * 60)
        else:
            return datetime.timedelta(0, number)
581664
def _delta_time(self, date_time):
        
        now = datetime.datetime.now(tzlocal())
        diff = date_time - now

        days = int(diff.days)
        hours = int(diff.seconds / 3600)
        minutes = int((diff.seconds / 60) - (hours * 60)) + 1
        total_minutes = int((diff.seconds / 60) + (days * 24 * 60)) + 1

        return {
            "days": days,
            "hours": hours,
            "minutes": minutes,
            "total_minutes": total_minutes,
        }
1329466
def memorized_timedelta(seconds):
    ''''''
    try:
        return _timedelta_cache[seconds]
    except KeyError:
        delta = timedelta(seconds=seconds)
        _timedelta_cache[seconds] = delta
        return delta
1041036
def _encode_datetime_with_cftime(dates, units, calendar):
    
    cftime = _import_cftime()

    if np.issubdtype(dates.dtype, np.datetime64):
        # numpy's broken datetime conversion only works for us precision
        dates = dates.astype('M8[us]').astype(datetime)

    def encode_datetime(d):
        return np.nan if d is None else cftime.date2num(d, units, calendar)

    return np.vectorize(encode_datetime)(dates)
445976
def get_mean_per_split(self):
        
        return [div_timedelta(sum(stopwatch.split_elapsed_time, datetime.timedelta()),
                              len(stopwatch.split_elapsed_time))
                if stopwatch.split_elapsed_time else datetime.timedelta()
                for stopwatch in self]
221353
def get_sample_times(self):
        
        if self._epoch is None:
            return Array(range(len(self))) * self._delta_t
        else:
            return Array(range(len(self))) * self._delta_t + float(self._epoch)
341692
function determineDeltas(sizes, column, step, min, isPercentageBased) {

        var result = sizes.slice(0);

        function generateZeros(array) {
          return Tools.map(array, function () {
            return 0;
          });
        }

        function onOneColumn() {
          var deltas;
          if (isPercentageBased) {
            // If we have one column in a percent based table, that column should be 100% of the width of the table.
            deltas = [100 - result[0]];
          } else {
            var newNext = Math.max(min, result[0] + step);
            deltas = [newNext - result[0]];
          }
          return deltas;
        }

        function onLeftOrMiddle(index, next) {

          var startZeros = generateZeros(result.slice(0, index));
          var endZeros = generateZeros(result.slice(next + 1));
          var deltas;

          if (step >= 0) {
            var newNext = Math.max(min, result[next] - step);
            deltas = startZeros.concat([step, newNext - result[next]]).concat(endZeros);
          } else {
            var newThis = Math.max(min, result[index] + step);
            var diffx = result[index] - newThis;
            deltas = startZeros.concat([newThis - result[index], diffx]).concat(endZeros);
          }

          return deltas;
        }

        function onRight(previous, index) {
          var startZeros = generateZeros(result.slice(0, index));
          var deltas;

          if (step >= 0) {
            deltas = startZeros.concat([step]);
          } else {
            var size = Math.max(min, result[index] + step);
            deltas = startZeros.concat([size - result[index]]);
          }

          return deltas;

        }

        var deltas;

        if (sizes.length === 0) { // No Columns
          deltas = [];
        } else if (sizes.length === 1) { // One Column
          deltas = onOneColumn();
        } else if (column === 0) { // Left Column
          deltas = onLeftOrMiddle(0, 1);
        } else if (column > 0 && column < sizes.length - 1) { // Middle Column
          deltas = onLeftOrMiddle(column, column + 1);
        } else if (column === sizes.length - 1) { // Right Column
          deltas = onRight(column - 1, column);
        } else {
          deltas = [];
        }

        return deltas;
      }
370891
def unique_array(arr):
    
    if not len(arr):
        return np.asarray(arr)
    elif pd:
        if isinstance(arr, np.ndarray) and arr.dtype.kind not in 'MO':
            # Avoid expensive unpacking if not potentially datetime
            return pd.unique(arr)

        values = []
        for v in arr:
            if (isinstance(v, datetime_types) and
                not isinstance(v, cftime_types)):
                v = pd.Timestamp(v).to_datetime64()
            values.append(v)
        return pd.unique(values)
    else:
        arr = np.asarray(arr)
        _, uniq_inds = np.unique(arr, return_index=True)
        return arr[np.sort(uniq_inds)]
1047108
def f_energy(ac_power, times):
    
    dt = np.diff(times)  # calculate timesteps
    # convert timedeltas to quantities
    dt = dt.astype('timedelta64[s]').astype('float') / sc_const.hour
    # energy accumulate during timestep
    energy = dt * (ac_power[:-1] + ac_power[1:]) / 2
    return energy, times[1:]
368186
def to_minutes(days=0, hours=0, minutes=0, seconds=0, milliseconds=0,
               round_to_int=True):
    
    total = float(days)*24*60 + float(hours)*60 + float(minutes) + \
        float(seconds)/60 + float(milliseconds)/1000/60
    return int(round(total)) if round_to_int else total
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)