Adapted from
        pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound
330443
def _maybe_cast_slice_bound(self, label, side, kind):
        """"""
        if isinstance(label, str):
            parsed, resolution = _parse_iso8601_with_reso(self.date_type,
                                                          label)
            start, end = _parsed_string_to_bounds(self.date_type, resolution,
                                                  parsed)
            if self.is_monotonic_decreasing and len(self) > 1:
                return end if side == 'left' else start
            return start if side == 'left' else end
        else:
            return label
704698
def time_slice(self, start, end):
        
        if start < self.start_time:
            raise ValueError('Time series does not contain a time as early as %s' % start)

        if end > self.end_time:
            raise ValueError('Time series does not contain a time as late as %s' % end)

        start_idx = int((start - self.start_time) * self.sample_rate)
        end_idx = int((end - self.start_time) * self.sample_rate)
        return self[start_idx:end_idx]
1026628
def compute_slice_bounds(slices, scs, shape):
    
    xidx, yidx = slices
    ys, xs = shape
    l, b, r, t = scs.bounds.lbrt()
    xdensity, ydensity = scs.xdensity, scs.ydensity
    xunit = (1./xdensity)
    yunit = (1./ydensity)
    if isinstance(l, datetime_types):
        xunit = np.timedelta64(int(round(xunit)), scs._time_unit)
    if isinstance(b, datetime_types):
        yunit = np.timedelta64(int(round(yunit)), scs._time_unit)
    if isinstance(xidx, slice):
        l = l if xidx.start is None else max(l, xidx.start)
        r = r if xidx.stop is None else min(r, xidx.stop)
    if isinstance(yidx, slice):
        b = b if yidx.start is None else max(b, yidx.start)
        t = t if yidx.stop is None else min(t, yidx.stop)
    bounds = BoundingBox(points=((l, b), (r, t)))

    # Apply new bounds
    slc = Slice(bounds, scs)

    # Apply scalar and list indices
    l, b, r, t = slc.compute_bounds(scs).lbrt()
    if not isinstance(xidx, slice):
        if not isinstance(xidx, (list, set)): xidx = [xidx]
        if len(xidx) > 1:
            xdensity = xdensity*(float(len(xidx))/xs)
        ls, rs = [], []
        for idx in xidx:
            xc, _ = scs.closest_cell_center(idx, b)
            ls.append(xc-xunit/2)
            rs.append(xc+xunit/2)
        l, r = np.min(ls), np.max(rs)
    elif not isinstance(yidx, slice):
        if not isinstance(yidx, (set, list)): yidx = [yidx]
        if len(yidx) > 1:
            ydensity = ydensity*(float(len(yidx))/ys)
        bs, ts = [], []
        for idx in yidx:
            _, yc = scs.closest_cell_center(l, idx)
            bs.append(yc-yunit/2)
            ts.append(yc+yunit/2)
        b, t = np.min(bs), np.max(ts)
    return BoundingBox(points=((l, b), (r, t)))
687817
def as_indexable(array):
    
    if isinstance(array, ExplicitlyIndexed):
        return array
    if isinstance(array, np.ndarray):
        return NumpyIndexingAdapter(array)
    if isinstance(array, pd.Index):
        return PandasIndexAdapter(array)
    if isinstance(array, dask_array_type):
        return DaskIndexingAdapter(array)
    raise TypeError('Invalid array type: {}'.format(type(array)))
442492
def pythonvaluetotime(time_val):
    ""
    if time_val is None:
        return None
    elif isinstance(time_val, numeric):
        return str(long(time_val * 1000.0))
    elif isinstance(time_val, date):
        dtlist = [time_val.year, time_val.month, time_val.day]
        if isinstance(time_val, datetime.datetime):
            dtlist += [time_val.hour, time_val.minute, time_val.second]
        else:
            dtlist += [0, 0, 0]
        return long(calendar.timegm(dtlist) * 1000.0)
    elif (isinstance(time_val, sequence)
                    and len(time_val) == 2):
        if all(isinstance(x, numeric) 
               for x in time_val):
            return ",".join(pythonvaluetotime(x) 
                            for x in time_val)
        elif all(isinstance(x, date) 
               for x in time_val):
            return ",".join(pythonvaluetotime(x) 
                            for x in time_val)
    raise ValueError(repr(time_val))
1288362
def _non_reducing_slice(slice_):
    
    # default to column slice, like DataFrame
    # ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
    kinds = (ABCSeries, np.ndarray, Index, list, str)
    if isinstance(slice_, kinds):
        slice_ = IndexSlice[:, slice_]

    def pred(part):
        # true when slice does *not* reduce, False when part is a tuple,
        # i.e. MultiIndex slice
        return ((isinstance(part, slice) or is_list_like(part))
                and not isinstance(part, tuple))

    if not is_list_like(slice_):
        if not isinstance(slice_, slice):
            # a 1-d slice, like df.loc[1]
            slice_ = [[slice_]]
        else:
            # slice(a, b, c)
            slice_ = [slice_]  # to tuplize later
    else:
        slice_ = [part if pred(part) else [part] for part in slice_]
    return tuple(slice_)
1156427
def has_data_for_dates(series_or_df, first_date, last_date):
    
    dts = series_or_df.index
    if not isinstance(dts, pd.DatetimeIndex):
        raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts))
    first, last = dts[[0, -1]]
    return (first <= first_date) and (last >= last_date)
255393
def nowrange(self, col, timeframe):
        
        df = self._nowrange(col, timeframe)
        if df is None:
            self.err("Can not select range data from now")
            return
        self.df = df
1194067
def exclude(self, data, range_obj):
        
        if isinstance(range_obj, (pd.DatetimeIndex, tuple)):
            range_obj = DateRange(range_obj[0], range_obj[-1])
        if 'date' in data.index.names:
            return data[(data.index.get_level_values('date') < range_obj.start) | (data.index.get_level_values('date') > range_obj.end)]
        elif 'date' in data.columns:
            return data[(data.date < range_obj.start) | (data.date > range_obj.end)]
        else:
            return data
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
1080485
def parse_data_type(self, index, **kwargs):
        """"""
        if not index.isValid():
            return False
        try:
            if kwargs['atype'] == "date":
                self._data[index.row()][index.column()] = \
                    datestr_to_datetime(self._data[index.row()][index.column()],
                                    kwargs['dayfirst']).date()
            elif kwargs['atype'] == "perc":
                _tmp = self._data[index.row()][index.column()].replace("%", "")
                self._data[index.row()][index.column()] = eval(_tmp)/100.
            elif kwargs['atype'] == "account":
                _tmp = self._data[index.row()][index.column()].replace(",", "")
                self._data[index.row()][index.column()] = eval(_tmp)
            elif kwargs['atype'] == "unicode":
                self._data[index.row()][index.column()] = to_text_string(
                    self._data[index.row()][index.column()])
            elif kwargs['atype'] == "int":
                self._data[index.row()][index.column()] = int(
                    self._data[index.row()][index.column()])
            elif kwargs['atype'] == "float":
                self._data[index.row()][index.column()] = float(
                    self._data[index.row()][index.column()])
            self.dataChanged.emit(index, index)
        except Exception as instance:
            print(instance)
1084871
def from_tushare(dataframe, dtype='day'):
    

    if dtype in ['day']:
        return QA_DataStruct_Stock_day(
            dataframe.assign(date=pd.to_datetime(dataframe.date)
                            ).set_index(['date',
                                         'code'],
                                        drop=False),
            dtype='stock_day'
        )
    elif dtype in ['min']:
        return QA_DataStruct_Stock_min(
            dataframe.assign(datetime=pd.to_datetime(dataframe.datetime)
                            ).set_index(['datetime',
                                         'code'],
                                        drop=False),
            dtype='stock_min'
        )
805866
def _cast(self, value, format=None, **opts):
        """"""
        if format is not None:
            return datetime.strptime(value, format)
        return dateutil.parser.parse(value)
716758
def _preprocess_for_cut(x):
    
    x_is_series = isinstance(x, Series)
    series_index = None
    name = None

    if x_is_series:
        series_index = x.index
        name = x.name

    # Check that the passed array is a Pandas or Numpy object
    # We don't want to strip away a Pandas data-type here (e.g. datetimetz)
    ndim = getattr(x, 'ndim', None)
    if ndim is None:
        x = np.asarray(x)
    if x.ndim != 1:
        raise ValueError("Input array must be 1 dimensional")

    return x_is_series, series_index, name, x
902614
def _datetime64_index(self, recarr):
        
        # TODO: Handle multi-indexes
        names = recarr.dtype.names
        for name in names:
            if recarr[name].dtype == DTN64_DTYPE:
                return name
        return None
103532
def _join_i8_wrapper(joinf, dtype, with_indexers=True):
        
        from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin

        @staticmethod
        def wrapper(left, right):
            if isinstance(left, (np.ndarray, ABCIndex, ABCSeries,
                                 DatetimeLikeArrayMixin)):
                left = left.view('i8')
            if isinstance(right, (np.ndarray, ABCIndex, ABCSeries,
                                  DatetimeLikeArrayMixin)):
                right = right.view('i8')
            results = joinf(left, right)
            if with_indexers:
                join_index, left_indexer, right_indexer = results
                join_index = join_index.view(dtype)
                return join_index, left_indexer, right_indexer
            return results

        return wrapper
605274
def _construct_timeseries(self, timeseries, constraints={}):
        
        self.response_from(timeseries, constraints)
        if self.response == None:
            return None
        return {'data':self.response['data'],
                'period':self.response['period'],
                'start time':datetime.datetime.fromtimestamp(self.response['start_time']),
                'end time':datetime.datetime.fromtimestamp(self.response['end_time'])}