Python pandas.tseries.offsets.Tick() Examples

The following are 30 code examples of pandas.tseries.offsets.Tick(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pandas.tseries.offsets , or try the search function .
Example #1
Source File: common.py    From gluon-ts with Apache License 2.0 6 votes vote down vote up
def process(string: str, freq: str) -> pd.Timestamp:
        """Create timestamp and align it according to frequency.
        """

        timestamp = pd.Timestamp(string, freq=freq)

        # operate on time information (days, hours, minute, second)
        if isinstance(timestamp.freq, Tick):
            return pd.Timestamp(
                timestamp.floor(timestamp.freq), timestamp.freq
            )

        # since we are only interested in the data piece, we normalize the
        # time information
        timestamp = timestamp.replace(
            hour=0, minute=0, second=0, microsecond=0, nanosecond=0
        )

        return timestamp.freq.rollforward(timestamp) 
Example #2
Source File: datetimes.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _add_offset(self, offset):
        assert not isinstance(offset, Tick)
        try:
            if self.tz is not None:
                values = self.tz_localize(None)
            else:
                values = self
            result = offset.apply_index(values)
            if self.tz is not None:
                result = result.tz_localize(self.tz)

        except NotImplementedError:
            warnings.warn("Non-vectorized DateOffset being applied to Series "
                          "or DatetimeIndex", PerformanceWarning)
            result = self.astype('O') + offset

        return type(self)._from_sequence(result, freq='infer') 
Example #3
Source File: resample.py    From Computable with MIT License 6 votes vote down vote up
def _get_range_edges(axis, offset, closed='left', base=0):
    if isinstance(offset, compat.string_types):
        offset = to_offset(offset)

    if isinstance(offset, Tick):
        day_nanos = _delta_to_nanoseconds(timedelta(1))
        # #1165
        if (day_nanos % offset.nanos) == 0:
            return _adjust_dates_anchored(axis[0], axis[-1], offset,
                                          closed=closed, base=base)

    first, last = axis[0], axis[-1]
    if not isinstance(offset, Tick):  # and first.time() != last.time():
        # hack!
        first = tools.normalize_date(first)
        last = tools.normalize_date(last)

    if closed == 'left':
        first = Timestamp(offset.rollback(first))
    else:
        first = Timestamp(first - offset)

    last = Timestamp(last + offset)

    return first, last 
Example #4
Source File: datetimes.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _add_delta(self, delta):
        """
        Add a timedelta-like, Tick, or TimedeltaIndex-like object
        to self, yielding a new DatetimeArray

        Parameters
        ----------
        other : {timedelta, np.timedelta64, Tick,
                 TimedeltaIndex, ndarray[timedelta64]}

        Returns
        -------
        result : DatetimeArray
        """
        new_values = super(DatetimeArray, self)._add_delta(delta)
        return type(self)._from_sequence(new_values, tz=self.tz, freq='infer')

    # -----------------------------------------------------------------
    # Timezone Conversion and Localization Methods 
Example #5
Source File: test_ticks.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_tick_division(cls):
    off = cls(10)

    assert off / cls(5) == 2
    assert off / 2 == cls(5)
    assert off / 2.0 == cls(5)

    assert off / off.delta == 1
    assert off / off.delta.to_timedelta64() == 1

    assert off / Nano(1) == off.delta / Nano(1).delta

    if cls is not Nano:
        # A case where we end up with a smaller class
        result = off / 1000
        assert isinstance(result, offsets.Tick)
        assert not isinstance(result, cls)
        assert result.delta == off.delta / 1000

    if cls._inc < Timedelta(seconds=1):
        # Case where we end up with a bigger class
        result = off / .001
        assert isinstance(result, offsets.Tick)
        assert not isinstance(result, cls)
        assert result.delta == off.delta / .001 
Example #6
Source File: period.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _from_datetime64(cls, data, freq, tz=None):
        """
        Construct a PeriodArray from a datetime64 array

        Parameters
        ----------
        data : ndarray[datetime64[ns], datetime64[ns, tz]]
        freq : str or Tick
        tz : tzinfo, optional

        Returns
        -------
        PeriodArray[freq]
        """
        data, freq = dt64arr_to_periodarr(data, freq, tz)
        return cls(data, freq=freq) 
Example #7
Source File: period.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _add_timedeltalike_scalar(self, other):
        """
        Parameters
        ----------
        other : timedelta, Tick, np.timedelta64

        Returns
        -------
        result : ndarray[int64]
        """
        assert isinstance(self.freq, Tick)  # checked by calling function
        assert isinstance(other, (timedelta, np.timedelta64, Tick))

        if notna(other):
            # special handling for np.timedelta64("NaT"), avoid calling
            #  _check_timedeltalike_freq_compat as that would raise TypeError
            other = self._check_timedeltalike_freq_compat(other)

        # Note: when calling parent class's _add_timedeltalike_scalar,
        #  it will call delta_to_nanoseconds(delta).  Because delta here
        #  is an integer, delta_to_nanoseconds will return it unchanged.
        ordinals = super(PeriodArray, self)._add_timedeltalike_scalar(other)
        return ordinals 
Example #8
Source File: index.py    From Computable with MIT License 6 votes vote down vote up
def _add_delta(self, delta):
        if isinstance(delta, (Tick, timedelta)):
            inc = offsets._delta_to_nanoseconds(delta)
            new_values = (self.asi8 + inc).view(_NS_DTYPE)
            tz = 'UTC' if self.tz is not None else None
            result = DatetimeIndex(new_values, tz=tz, freq='infer')
            utc = _utc()
            if self.tz is not None and self.tz is not utc:
                result = result.tz_convert(self.tz)
        elif isinstance(delta, np.timedelta64):
            new_values = self.to_series() + delta
            result = DatetimeIndex(new_values, tz=self.tz, freq='infer')
        else:
            new_values = self.astype('O') + delta
            result = DatetimeIndex(new_values, tz=self.tz, freq='infer')
        return result 
Example #9
Source File: test_ticks.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_tick_division(cls):
    off = cls(10)

    assert off / cls(5) == 2
    assert off / 2 == cls(5)
    assert off / 2.0 == cls(5)

    assert off / off.delta == 1
    assert off / off.delta.to_timedelta64() == 1

    assert off / Nano(1) == off.delta / Nano(1).delta

    if cls is not Nano:
        # A case where we end up with a smaller class
        result = off / 1000
        assert isinstance(result, offsets.Tick)
        assert not isinstance(result, cls)
        assert result.delta == off.delta / 1000

    if cls._inc < Timedelta(seconds=1):
        # Case where we end up with a bigger class
        result = off / .001
        assert isinstance(result, offsets.Tick)
        assert not isinstance(result, cls)
        assert result.delta == off.delta / .001 
Example #10
Source File: datetimes.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _add_offset(self, offset):
        assert not isinstance(offset, Tick)
        try:
            if self.tz is not None:
                values = self.tz_localize(None)
            else:
                values = self
            result = offset.apply_index(values)
            if self.tz is not None:
                result = result.tz_localize(self.tz)

        except NotImplementedError:
            warnings.warn("Non-vectorized DateOffset being applied to Series "
                          "or DatetimeIndex", PerformanceWarning)
            result = self.astype('O') + offset

        return type(self)._from_sequence(result, freq='infer') 
Example #11
Source File: datetimes.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _add_delta(self, delta):
        """
        Add a timedelta-like, Tick, or TimedeltaIndex-like object
        to self, yielding a new DatetimeArray

        Parameters
        ----------
        other : {timedelta, np.timedelta64, Tick,
                 TimedeltaIndex, ndarray[timedelta64]}

        Returns
        -------
        result : DatetimeArray
        """
        new_values = super(DatetimeArray, self)._add_delta(delta)
        return type(self)._from_sequence(new_values, tz=self.tz, freq='infer')

    # -----------------------------------------------------------------
    # Timezone Conversion and Localization Methods 
Example #12
Source File: period.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _from_datetime64(cls, data, freq, tz=None):
        """
        Construct a PeriodArray from a datetime64 array

        Parameters
        ----------
        data : ndarray[datetime64[ns], datetime64[ns, tz]]
        freq : str or Tick
        tz : tzinfo, optional

        Returns
        -------
        PeriodArray[freq]
        """
        data, freq = dt64arr_to_periodarr(data, freq, tz)
        return cls(data, freq=freq) 
Example #13
Source File: period.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _add_timedeltalike_scalar(self, other):
        """
        Parameters
        ----------
        other : timedelta, Tick, np.timedelta64

        Returns
        -------
        result : ndarray[int64]
        """
        assert isinstance(self.freq, Tick)  # checked by calling function
        assert isinstance(other, (timedelta, np.timedelta64, Tick))

        if notna(other):
            # special handling for np.timedelta64("NaT"), avoid calling
            #  _check_timedeltalike_freq_compat as that would raise TypeError
            other = self._check_timedeltalike_freq_compat(other)

        # Note: when calling parent class's _add_timedeltalike_scalar,
        #  it will call delta_to_nanoseconds(delta).  Because delta here
        #  is an integer, delta_to_nanoseconds will return it unchanged.
        ordinals = super(PeriodArray, self)._add_timedeltalike_scalar(other)
        return ordinals 
Example #14
Source File: test_ticks.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_tick_division(cls):
    off = cls(10)

    assert off / cls(5) == 2
    assert off / 2 == cls(5)
    assert off / 2.0 == cls(5)

    assert off / off.delta == 1
    assert off / off.delta.to_timedelta64() == 1

    assert off / Nano(1) == off.delta / Nano(1).delta

    if cls is not Nano:
        # A case where we end up with a smaller class
        result = off / 1000
        assert isinstance(result, offsets.Tick)
        assert not isinstance(result, cls)
        assert result.delta == off.delta / 1000

    if cls._inc < Timedelta(seconds=1):
        # Case where we end up with a bigger class
        result = off / .001
        assert isinstance(result, offsets.Tick)
        assert not isinstance(result, cls)
        assert result.delta == off.delta / .001 
Example #15
Source File: resample.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_range_edges(first, last, offset, closed='left', base=0):
    if isinstance(offset, compat.string_types):
        offset = to_offset(offset)

    if isinstance(offset, Tick):
        is_day = isinstance(offset, Day)
        day_nanos = _delta_to_nanoseconds(timedelta(1))

        # #1165
        if (is_day and day_nanos % offset.nanos == 0) or not is_day:
            return _adjust_dates_anchored(first, last, offset,
                                          closed=closed, base=base)

    if not isinstance(offset, Tick):  # and first.time() != last.time():
        # hack!
        first = first.normalize()
        last = last.normalize()

    if closed == 'left':
        first = Timestamp(offset.rollback(first))
    else:
        first = Timestamp(first - offset)

    last = Timestamp(last + offset)

    return first, last 
Example #16
Source File: period.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _maybe_convert_timedelta(self, other):
        if isinstance(
                other, (timedelta, np.timedelta64, offsets.Tick, np.ndarray)):
            offset = frequencies.to_offset(self.freq.rule_code)
            if isinstance(offset, offsets.Tick):
                if isinstance(other, np.ndarray):
                    nanos = np.vectorize(tslib._delta_to_nanoseconds)(other)
                else:
                    nanos = tslib._delta_to_nanoseconds(other)
                offset_nanos = tslib._delta_to_nanoseconds(offset)
                check = np.all(nanos % offset_nanos == 0)
                if check:
                    return nanos // offset_nanos
        elif isinstance(other, offsets.DateOffset):
            freqstr = other.rule_code
            base = frequencies.get_base_alias(freqstr)
            if base == self.freq.rule_code:
                return other.n
            msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr)
            raise IncompatibleFrequency(msg)
        elif isinstance(other, np.ndarray):
            if is_integer_dtype(other):
                return other
            elif is_timedelta64_dtype(other):
                offset = frequencies.to_offset(self.freq)
                if isinstance(offset, offsets.Tick):
                    nanos = tslib._delta_to_nanoseconds(other)
                    offset_nanos = tslib._delta_to_nanoseconds(offset)
                    if (nanos % offset_nanos).all() == 0:
                        return nanos // offset_nanos
        elif is_integer(other):
            # integer is passed to .shift via
            # _add_datetimelike_methods basically
            # but ufunc may pass integer to _add_delta
            return other
        # raise when input doesn't have freq
        msg = "Input has different freq from PeriodIndex(freq={0})"
        raise IncompatibleFrequency(msg.format(self.freqstr)) 
Example #17
Source File: timedeltas.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _add_delta(self, delta):
        if isinstance(delta, (Tick, timedelta, np.timedelta64)):
            new_values = self._add_delta_td(delta)
            name = self.name
        elif isinstance(delta, TimedeltaIndex):
            new_values = self._add_delta_tdi(delta)
            # update name when delta is index
            name = com._maybe_match_name(self, delta)
        else:
            raise ValueError("cannot add the type {0} to a TimedeltaIndex"
                             .format(type(delta)))

        result = TimedeltaIndex(new_values, freq='infer', name=name)
        return result 
Example #18
Source File: resample.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _get_range_edges(first, last, offset, closed='left', base=0):
    if isinstance(offset, compat.string_types):
        offset = to_offset(offset)

    if isinstance(offset, Tick):
        is_day = isinstance(offset, Day)
        day_nanos = _delta_to_nanoseconds(timedelta(1))

        # #1165
        if (is_day and day_nanos % offset.nanos == 0) or not is_day:
            return _adjust_dates_anchored(first, last, offset,
                                          closed=closed, base=base)

    if not isinstance(offset, Tick):  # and first.time() != last.time():
        # hack!
        first = first.normalize()
        last = last.normalize()

    if closed == 'left':
        first = Timestamp(offset.rollback(first))
    else:
        first = Timestamp(first - offset)

    last = Timestamp(last + offset)

    return first, last 
Example #19
Source File: test_ticks.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_tick_add_sub(cls, n, m):
    # For all Tick subclasses and all integers n, m, we should have
    # tick(n) + tick(m) == tick(n+m)
    # tick(n) - tick(m) == tick(n-m)
    left = cls(n)
    right = cls(m)
    expected = cls(n + m)

    assert left + right == expected
    assert left.apply(right) == expected

    expected = cls(n - m)
    assert left - right == expected 
Example #20
Source File: datetimes.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _maybe_localize_point(ts, is_none, is_not_none, freq, tz):
    """
    Localize a start or end Timestamp to the timezone of the corresponding
    start or end Timestamp

    Parameters
    ----------
    ts : start or end Timestamp to potentially localize
    is_none : argument that should be None
    is_not_none : argument that should not be None
    freq : Tick, DateOffset, or None
    tz : str, timezone object or None

    Returns
    -------
    ts : Timestamp
    """
    # Make sure start and end are timezone localized if:
    # 1) freq = a Timedelta-like frequency (Tick)
    # 2) freq = None i.e. generating a linspaced range
    if isinstance(freq, Tick) or freq is None:
        localize_args = {'tz': tz, 'ambiguous': False}
    else:
        localize_args = {'tz': None}
    if is_none is None and is_not_none is not None:
        ts = ts.tz_localize(**localize_args)
    return ts 
Example #21
Source File: timedeltas.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def __rdivmod__(self, other):
        # Note: This is a naive implementation, can likely be optimized
        if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
            return NotImplemented

        other = lib.item_from_zerodim(other)
        if isinstance(other, (timedelta, np.timedelta64, Tick)):
            other = Timedelta(other)

        res1 = other // self
        res2 = other - res1 * self
        return res1, res2

    # Note: TimedeltaIndex overrides this in call to cls._add_numeric_methods 
Example #22
Source File: timedeltas.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def __rmod__(self, other):
        # Note: This is a naive implementation, can likely be optimized
        if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
            return NotImplemented

        other = lib.item_from_zerodim(other)
        if isinstance(other, (timedelta, np.timedelta64, Tick)):
            other = Timedelta(other)
        return other - (other // self) * self 
Example #23
Source File: timedeltas.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def __mod__(self, other):
        # Note: This is a naive implementation, can likely be optimized
        if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
            return NotImplemented

        other = lib.item_from_zerodim(other)
        if isinstance(other, (timedelta, np.timedelta64, Tick)):
            other = Timedelta(other)
        return self - (self // other) * other 
Example #24
Source File: timedeltas.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _add_offset(self, other):
        assert not isinstance(other, Tick)
        raise TypeError("cannot add the type {typ} to a {cls}"
                        .format(typ=type(other).__name__,
                                cls=type(self).__name__)) 
Example #25
Source File: timedeltas.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _validate_fill_value(self, fill_value):
        if isna(fill_value):
            fill_value = iNaT
        elif isinstance(fill_value, (timedelta, np.timedelta64, Tick)):
            fill_value = Timedelta(fill_value).value
        else:
            raise ValueError("'fill_value' should be a Timedelta. "
                             "Got '{got}'.".format(got=fill_value))
        return fill_value 
Example #26
Source File: timedeltas.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _is_convertible_to_td(key):
    return isinstance(key, (Tick, timedelta,
                            np.timedelta64, compat.string_types)) 
Example #27
Source File: datetimes.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _maybe_localize_point(ts, is_none, is_not_none, freq, tz):
    """
    Localize a start or end Timestamp to the timezone of the corresponding
    start or end Timestamp

    Parameters
    ----------
    ts : start or end Timestamp to potentially localize
    is_none : argument that should be None
    is_not_none : argument that should not be None
    freq : Tick, DateOffset, or None
    tz : str, timezone object or None

    Returns
    -------
    ts : Timestamp
    """
    # Make sure start and end are timezone localized if:
    # 1) freq = a Timedelta-like frequency (Tick)
    # 2) freq = None i.e. generating a linspaced range
    if isinstance(freq, Tick) or freq is None:
        localize_args = {'tz': tz, 'ambiguous': False}
    else:
        localize_args = {'tz': None}
    if is_none is None and is_not_none is not None:
        ts = ts.tz_localize(**localize_args)
    return ts 
Example #28
Source File: datetimelike.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _addsub_int_array(self, other, op):
        """
        Add or subtract array-like of integers equivalent to applying
        `_time_shift` pointwise.

        Parameters
        ----------
        other : Index, ExtensionArray, np.ndarray
            integer-dtype
        op : {operator.add, operator.sub}

        Returns
        -------
        result : same class as self
        """
        # _addsub_int_array is overriden by PeriodArray
        assert not is_period_dtype(self)
        assert op in [operator.add, operator.sub]

        if self.freq is None:
            # GH#19123
            raise NullFrequencyError("Cannot shift with no freq")

        elif isinstance(self.freq, Tick):
            # easy case where we can convert to timedelta64 operation
            td = Timedelta(self.freq)
            return op(self, td * other)

        # We should only get here with DatetimeIndex; dispatch
        # to _addsub_offset_array
        assert not is_timedelta64_dtype(self)
        return op(self, np.array(other) * self.freq) 
Example #29
Source File: timedeltas.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _is_convertible_to_td(key):
    return isinstance(key, (Tick, timedelta,
                            np.timedelta64, compat.string_types)) 
Example #30
Source File: period.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _add_offset(self, other):
        assert not isinstance(other, Tick)
        base = libfrequencies.get_base_alias(other.rule_code)
        if base != self.freq.rule_code:
            _raise_on_incompatible(self, other)

        # Note: when calling parent class's _add_timedeltalike_scalar,
        #  it will call delta_to_nanoseconds(delta).  Because delta here
        #  is an integer, delta_to_nanoseconds will return it unchanged.
        result = super(PeriodArray, self)._add_timedeltalike_scalar(other.n)
        return type(self)(result, freq=self.freq)