subtract DatetimeArray/Index or ndarray[datetime64]
173017
def _sub_datetime_arraylike(self, other):
        """"""
        if len(self) != len(other):
            raise ValueError("cannot add indices of unequal length")

        if isinstance(other, np.ndarray):
            assert is_datetime64_dtype(other)
            other = type(self)(other)

        if not self._has_same_tz(other):
            # require tz compat
            raise TypeError("{cls} subtraction must have the same "
                            "timezones or no timezones"
                            .format(cls=type(self).__name__))

        self_i8 = self.asi8
        other_i8 = other.asi8
        arr_mask = self._isnan | other._isnan
        new_values = checked_add_with_arr(self_i8, -other_i8,
                                          arr_mask=arr_mask)
        if self._hasnans or other._hasnans:
            new_values[arr_mask] = iNaT
        return new_values.view('timedelta64[ns]')
1309841
def dateTimeRect( self, dateTime ):
        
        data = self._dateTimeGrid.get(dateTime.toTime_t())
        if ( data ):
            return QRectF(data[1])
        return QRectF()
238716
def _strip_datetime(self, sub_line):
        """"""
        try:
            begin = sub_line.index(']')
        except ValueError:
            return sub_line
        else:
            # create a "" in place character for the beginnings..
            # needed when interleaving the lists
            sub = sub_line[begin + 1:]
            return sub
1033079
def is_np_datetime_like(dtype: Union[str, np.dtype]) -> bool:
    
    return (np.issubdtype(dtype, np.datetime64) or
            np.issubdtype(dtype, np.timedelta64))
313923
def _add_datetime_arraylike(self, other):
        
        if isinstance(other, np.ndarray):
            # At this point we have already checked that dtype is datetime64
            from pandas.core.arrays import DatetimeArray
            other = DatetimeArray(other)

        # defer to implementation in DatetimeArray
        return other + self
1371862
def _time_reduce(self, arr, reduction):
        """"""
        if self.dtype_in_time == 'av' or not self.def_time:
            return arr
        reductions = {
            'ts': lambda xarr: xarr,
            'av': lambda xarr: xarr.mean(internal_names.YEAR_STR),
            'std': lambda xarr: xarr.std(internal_names.YEAR_STR),
            }
        try:
            return reductions[reduction](arr)
        except KeyError:
            raise ValueError("Specified time-reduction method '{}' is not "
                             "supported".format(reduction))
1370692
def rungtd1d(time: Union[datetime, str, np.ndarray],
             altkm: np.ndarray,
             glat: float, glon: float) -> xarray.Dataset:
    
    time = todt64(time)
    # %% get solar parameters for date
    f107Ap = gi.getApF107(time, smoothdays=81)
    f107a = f107Ap['f107s'].item()
    f107 = f107Ap['f107'].item()
    Ap = f107Ap['Ap'].item()
# %% dimensions
    altkm = np.atleast_1d(altkm)
    assert altkm.ndim == 1
    assert isinstance(glon, (int, float))
    assert isinstance(glat, (int, float))
    assert isinstance(time, np.datetime64) or (time.size == 1 and isinstance(
        time[0], np.datetime64)), 'if you have multiple times, for loop over them'

# don't check ap, too complicated
    assert isinstance(MASS, (float, int))
    assert len(TSELECOPS) == 25
# %%
    gtd7.tselec(TSELECOPS)  # like the msis_driver example

    iyd, utsec, stl = datetime2gtd(time, glon)
    altkm = np.atleast_1d(altkm)

    gtd7.meters(1)  # makes output in m^-3 and kg/m^-3
# %%
    if isinstance(Ap, (float, int)):
        Ap = [Ap]*7  # even if SW(9) == 1 due to f2py needs for array

    dens = np.empty((altkm.size, len(species)))
    temp = np.empty((altkm.size, len(ttypes)))
    for i, a in enumerate(altkm):
        dens[i, :], temp[i, :] = gtd7.gtd7(iyd, utsec, a, glat, glon, stl, f107a, f107, Ap, MASS)

    dsf = {k: (('time', 'alt_km', 'lat', 'lon'), v[None, :, None, None]) for (k, v) in zip(species, dens.T)}
    dsf.update({'Tn':  (('time', 'alt_km', 'lat', 'lon'), temp[:, 1][None, :, None, None]),
                'Texo': (('time', 'alt_km', 'lat', 'lon'), temp[:, 0][None, :, None, None])})

    atmos = xarray.Dataset(dsf,
                           coords={'time': time.astype(datetime), 'alt_km': altkm, 'lat': [glat], 'lon': [glon], },
                           attrs={'Ap': Ap, 'f107': f107, 'f107a': f107a,
                                  'species': species})

    return atmos
406485
def absdatetime(ts, default=None):
    """"""
    if ts is None:
        ts = default
    if isinstance(ts, dict):
        ts = timedelta(**ts)
    if isinstance(ts, timedelta):
        ts = now() + ts
    if isinstance(ts, datetime):
        return ts
    return None
657155
def subtract_days(self, days: int) -> datetime:
        
        self.value = self.value - relativedelta(days=days)
        return self.value
1158848
def sanitize_index(data, index, copy=False):
    

    if index is None:
        return data

    if len(data) != len(index):
        raise ValueError('Length of values does not match length of index')

    if isinstance(data, ABCIndexClass) and not copy:
        pass
    elif isinstance(data, (ABCPeriodIndex, ABCDatetimeIndex)):
        data = data._values
        if copy:
            data = data.copy()

    elif isinstance(data, np.ndarray):

        # coerce datetimelike types
        if data.dtype.kind in ['M', 'm']:
            data = sanitize_array(data, index, copy=copy)

    return data
1233611
def getyrdoy(date):
    """"""

    try:
        doy = date.toordinal()-datetime(date.year,1,1).toordinal()+1
    except AttributeError:
        raise AttributeError("Must supply a pandas datetime object or " +
                             "equivalent")
    else:
        return date.year, doy
354687
def load_with_datetime(pairs):
    """"""
    d = {}
    for k, v in pairs:
        if isinstance(v, basestring):
            try:
                d[k] = dateutil.parser.parse(v)
            except ValueError:
                d[k] = v
        else:
            d[k] = v             
    return d
895861
def format_items(x):
    """"""
    x = np.asarray(x)
    timedelta_format = 'datetime'
    if np.issubdtype(x.dtype, np.timedelta64):
        x = np.asarray(x, dtype='timedelta64[ns]')
        day_part = (x[~pd.isnull(x)]
                    .astype('timedelta64[D]')
                    .astype('timedelta64[ns]'))
        time_needed = x[~pd.isnull(x)] != day_part
        day_needed = day_part != np.timedelta64(0, 'ns')
        if np.logical_not(day_needed).all():
            timedelta_format = 'time'
        elif np.logical_not(time_needed).all():
            timedelta_format = 'date'

    formatted = [format_item(xi, timedelta_format) for xi in x]
    return formatted
192539
def datetime2ole(dt):
    """"""
    delta = dt - OLE_TIME_ZERO
    delta_float = delta / datetime.timedelta(days=1)  # trick from SO
    return delta_float
596804
def index(self, date):
        
        for (i, (start, end, ruler)) in enumerate(self.table):
            if start <= date.jd <= end:
                return i
        return None
19232
def swap_time_and_batch_axes(inputs):
  """"""
  transposed_axes = tf.concat([[1, 0], tf.range(2, tf.rank(inputs))], axis=0)
  return tf.transpose(inputs, transposed_axes)
732481
def timestamp_from_datetime(date_time):
    """"""
    if date_time.tzinfo is None:
      return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hour,
                          date_time.minute, date_time.second,
                          -1, -1, -1)) + date_time.microsecond / 1e6
    return (date_time - _EPOCH).total_seconds()