Python pandas.tseries.offsets.DateOffset() Examples
The following are 30
code examples of pandas.tseries.offsets.DateOffset().
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: test_offsets.py From vnpy_crypto with MIT License | 6 votes |
def _get_offset(self, klass, value=1, normalize=False): # create instance from offset class if klass is FY5253: klass = klass(n=value, startingMonth=1, weekday=1, variation='last', normalize=normalize) elif klass is FY5253Quarter: klass = klass(n=value, startingMonth=1, weekday=1, qtr_with_extra_week=1, variation='last', normalize=normalize) elif klass is LastWeekOfMonth: klass = klass(n=value, weekday=5, normalize=normalize) elif klass is WeekOfMonth: klass = klass(n=value, week=1, weekday=5, normalize=normalize) elif klass is Week: klass = klass(n=value, weekday=5, normalize=normalize) elif klass is DateOffset: klass = klass(days=value, normalize=normalize) else: try: klass = klass(value, normalize=normalize) except Exception: klass = klass(normalize=normalize) return klass
Example #2
Source File: test_pandas_store.py From arctic with GNU Lesser General Public License v2.1 | 6 votes |
def test_daterange(library, df, assert_equal): df.index.name = 'idx' df.name = 'FOO' library.write('MYARR', df) # whole array saved_arr = library.read('MYARR').data assert_equal(df, saved_arr) assert_equal(df, library.read('MYARR', date_range=DateRange(df.index[0])).data) assert_equal(df, library.read('MYARR', date_range=DateRange(df.index[0], df.index[-1])).data) assert_equal(df, library.read('MYARR', date_range=DateRange()).data) assert_equal(df[df.index[10]:], library.read('MYARR', date_range=DateRange(df.index[10])).data) assert_equal(df[:df.index[10]], library.read('MYARR', date_range=DateRange(end=df.index[10])).data) assert_equal(df[df.index[-1]:], library.read('MYARR', date_range=DateRange(df.index[-1])).data) assert_equal(df[df.index[-1]:], library.read('MYARR', date_range=DateRange(df.index[-1], df.index[-1])).data) assert_equal(df[df.index[0]:df.index[0]], library.read('MYARR', date_range=DateRange(df.index[0], df.index[0])).data) assert_equal(df[:df.index[0]], library.read('MYARR', date_range=DateRange(end=df.index[0])).data) assert_equal(df[df.index[0] - DateOffset(days=1):], library.read('MYARR', date_range=DateRange(df.index[0] - DateOffset(days=1))).data) assert_equal(df[df.index[-1] + DateOffset(days=1):], library.read('MYARR', date_range=DateRange(df.index[-1] + DateOffset(days=1))).data) assert len(library.read('MYARR', date_range=DateRange(dt(1950, 1, 1), dt(1951, 1, 1))).data) == 0 assert len(library.read('MYARR', date_range=DateRange(dt(2091, 1, 1), dt(2091, 1, 1))).data) == 0
Example #3
Source File: _timeseries.py From recruit with Apache License 2.0 | 6 votes |
def _get_freq(ax, series): # get frequency from data freq = getattr(series.index, 'freq', None) if freq is None: freq = getattr(series.index, 'inferred_freq', None) ax_freq = _get_ax_freq(ax) # use axes freq if no data freq if freq is None: freq = ax_freq # get the period frequency if isinstance(freq, DateOffset): freq = freq.rule_code else: freq = get_base_alias(freq) freq = frequencies.get_period_alias(freq) return freq, ax_freq
Example #4
Source File: plotting.py From Computable with MIT License | 6 votes |
def _get_freq(ax, series): # get frequency from data freq = getattr(series.index, 'freq', None) if freq is None: freq = getattr(series.index, 'inferred_freq', None) ax_freq = getattr(ax, 'freq', None) # use axes freq if no data freq if freq is None: freq = ax_freq # get the period frequency if isinstance(freq, DateOffset): freq = freq.rule_code else: freq = frequencies.get_base_alias(freq) freq = frequencies.get_period_alias(freq) return freq
Example #5
Source File: resample.py From vnpy_crypto with MIT License | 6 votes |
def _apply_loffset(self, result): """ if loffset is set, offset the result index This is NOT an idempotent routine, it will be applied exactly once to the result. Parameters ---------- result : Series or DataFrame the result of resample """ needs_offset = ( isinstance(self.loffset, (DateOffset, timedelta)) and isinstance(result.index, DatetimeIndex) and len(result.index) > 0 ) if needs_offset: result.index = result.index + self.loffset self.loffset = None return result
Example #6
Source File: dtypes.py From vnpy_crypto with MIT License | 6 votes |
def __new__(cls, freq=None): """ Parameters ---------- freq : frequency """ if isinstance(freq, PeriodDtype): return freq elif freq is None: # empty constructor for pickle compat return object.__new__(cls) from pandas.tseries.offsets import DateOffset if not isinstance(freq, DateOffset): freq = cls._parse_dtype_strict(freq) try: return cls._cache[freq.freqstr] except KeyError: u = object.__new__(cls) u.freq = freq cls._cache[freq.freqstr] = u return u
Example #7
Source File: datetimelike.py From recruit with Apache License 2.0 | 6 votes |
def maybe_infer_freq(freq): """ Comparing a DateOffset to the string "infer" raises, so we need to be careful about comparisons. Make a dummy variable `freq_infer` to signify the case where the given freq is "infer" and set freq to None to avoid comparison trouble later on. Parameters ---------- freq : {DateOffset, None, str} Returns ------- freq : {DateOffset, None} freq_infer : bool """ freq_infer = False if not isinstance(freq, DateOffset): # if a passed freq is None, don't infer automatically if freq != 'infer': freq = frequencies.to_offset(freq) else: freq_infer = True freq = None return freq, freq_infer
Example #8
Source File: datetimelike.py From vnpy_crypto with MIT License | 6 votes |
def _validate_frequency(cls, index, freq, **kwargs): """ Validate that a frequency is compatible with the values of a given DatetimeIndex or TimedeltaIndex Parameters ---------- index : DatetimeIndex or TimedeltaIndex The index on which to determine if the given frequency is valid freq : DateOffset The frequency to validate """ inferred = index.inferred_freq if index.empty or inferred == freq.freqstr: return None on_freq = cls._generate( index[0], None, len(index), None, freq, **kwargs) if not np.array_equal(index.asi8, on_freq.asi8): msg = ('Inferred frequency {infer} from passed values does not ' 'conform to passed frequency {passed}') raise ValueError(msg.format(infer=inferred, passed=freq.freqstr))
Example #9
Source File: dtypes.py From recruit with Apache License 2.0 | 6 votes |
def __new__(cls, freq=None): """ Parameters ---------- freq : frequency """ if isinstance(freq, PeriodDtype): return freq elif freq is None: # empty constructor for pickle compat return object.__new__(cls) from pandas.tseries.offsets import DateOffset if not isinstance(freq, DateOffset): freq = cls._parse_dtype_strict(freq) try: return cls._cache[freq.freqstr] except KeyError: u = object.__new__(cls) u.freq = freq cls._cache[freq.freqstr] = u return u
Example #10
Source File: resample.py From recruit with Apache License 2.0 | 6 votes |
def _apply_loffset(self, result): """ If loffset is set, offset the result index. This is NOT an idempotent routine, it will be applied exactly once to the result. Parameters ---------- result : Series or DataFrame the result of resample """ needs_offset = ( isinstance(self.loffset, (DateOffset, timedelta, np.timedelta64)) and isinstance(result.index, DatetimeIndex) and len(result.index) > 0 ) if needs_offset: result.index = result.index + self.loffset self.loffset = None return result
Example #11
Source File: _timeseries.py From vnpy_crypto with MIT License | 6 votes |
def _get_freq(ax, series): # get frequency from data freq = getattr(series.index, 'freq', None) if freq is None: freq = getattr(series.index, 'inferred_freq', None) ax_freq = _get_ax_freq(ax) # use axes freq if no data freq if freq is None: freq = ax_freq # get the period frequency if isinstance(freq, DateOffset): freq = freq.rule_code else: freq = frequencies.get_base_alias(freq) freq = frequencies.get_period_alias(freq) return freq, ax_freq
Example #12
Source File: index.py From Computable with MIT License | 5 votes |
def shift(self, n, freq=None): """ Specialized shift which produces a DatetimeIndex Parameters ---------- n : int Periods to shift by freq : DateOffset or timedelta-like, optional Returns ------- shifted : DatetimeIndex """ if freq is not None and freq != self.offset: if isinstance(freq, compat.string_types): freq = to_offset(freq) result = Index.shift(self, n, freq) result.tz = self.tz return result if n == 0: # immutable so OK return self if self.offset is None: raise ValueError("Cannot shift with no offset") start = self[0] + n * self.offset end = self[-1] + n * self.offset return DatetimeIndex(start=start, end=end, freq=self.offset, name=self.name, tz=self.tz)
Example #13
Source File: index.py From Computable with MIT License | 5 votes |
def __sub__(self, other): if isinstance(other, Index): return self.diff(other) elif isinstance(other, (DateOffset, timedelta)): return self._add_delta(-other) elif isinstance(other, np.timedelta64): return self._add_delta(-other) elif com.is_integer(other): return self.shift(-other) else: # pragma: no cover raise TypeError(other)
Example #14
Source File: index.py From Computable with MIT License | 5 votes |
def __add__(self, other): if isinstance(other, Index): return self.union(other) elif isinstance(other, (DateOffset, timedelta)): return self._add_delta(other) elif isinstance(other, np.timedelta64): return self._add_delta(other) elif com.is_integer(other): return self.shift(other) else: # pragma: no cover raise TypeError(other)
Example #15
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_validate_n_error(): with pytest.raises(TypeError): DateOffset(n='Doh!') with pytest.raises(TypeError): MonthBegin(n=timedelta(1)) with pytest.raises(TypeError): BDay(n=np.array([1, 2], dtype=np.int64))
Example #16
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_get_offset_day_error(): # subclass of _BaseOffset must override _day_opt attribute, or we should # get a NotImplementedError with pytest.raises(NotImplementedError): DateOffset()._get_offset_day(datetime.now())
Example #17
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def _test_offset(self, offset_name, offset_n, tstart, expected_utc_offset): offset = DateOffset(**{offset_name: offset_n}) t = tstart + offset if expected_utc_offset is not None: assert get_utc_offset_hours(t) == expected_utc_offset if offset_name == 'weeks': # dates should match assert t.date() == timedelta(days=7 * offset.kwds[ 'weeks']) + tstart.date() # expect the same day of week, hour of day, minute, second, ... assert (t.dayofweek == tstart.dayofweek and t.hour == tstart.hour and t.minute == tstart.minute and t.second == tstart.second) elif offset_name == 'days': # dates should match assert timedelta(offset.kwds['days']) + tstart.date() == t.date() # expect the same hour of day, minute, second, ... assert (t.hour == tstart.hour and t.minute == tstart.minute and t.second == tstart.second) elif offset_name in self.valid_date_offsets_singular: # expect the singular offset value to match between tstart and t datepart_offset = getattr(t, offset_name if offset_name != 'weekday' else 'dayofweek') assert datepart_offset == offset.kwds[offset_name] else: # the offset should be the same as if it was done in UTC assert (t == (tstart.tz_convert('UTC') + offset) .tz_convert('US/Pacific'))
Example #18
Source File: test_offsets.py From Computable with MIT License | 5 votes |
def test_repr(self): repr(DateOffset()) repr(DateOffset(2)) repr(2 * DateOffset()) repr(2 * DateOffset(months=2))
Example #19
Source File: test_offsets.py From Computable with MIT License | 5 votes |
def test_dateoffset_misc(): oset = offsets.DateOffset(months=2, days=4) # it works result = oset.freqstr assert(not offsets.DateOffset(months=2) == 2)
Example #20
Source File: test_plotting.py From Computable with MIT License | 5 votes |
def _check_plot_works(f, freq=None, series=None, *args, **kwargs): import matplotlib.pyplot as plt fig = plt.gcf() try: plt.clf() ax = fig.add_subplot(211) orig_ax = kwargs.pop('ax', plt.gca()) orig_axfreq = getattr(orig_ax, 'freq', None) ret = f(*args, **kwargs) assert ret is not None # do something more intelligent ax = kwargs.pop('ax', plt.gca()) if series is not None: dfreq = series.index.freq if isinstance(dfreq, DateOffset): dfreq = dfreq.rule_code if orig_axfreq is None: assert ax.freq == dfreq if freq is not None and orig_axfreq is None: assert ax.freq == freq ax = fig.add_subplot(212) try: kwargs['ax'] = ax ret = f(*args, **kwargs) assert ret is not None # do something more intelligent except Exception: pass with ensure_clean(return_filelike=True) as path: plt.savefig(path) finally: plt.close(fig)
Example #21
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_dateoffset_misc(): oset = offsets.DateOffset(months=2, days=4) # it works oset.freqstr assert (not offsets.DateOffset(months=2) == 2)
Example #22
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_copy(self): assert (DateOffset(months=2).copy() == DateOffset(months=2))
Example #23
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_constructor(self): assert ((self.d + DateOffset(months=2)) == datetime(2008, 3, 2)) assert ((self.d - DateOffset(months=2)) == datetime(2007, 11, 2)) assert ((self.d + DateOffset(2)) == datetime(2008, 1, 4)) assert not DateOffset(2).isAnchored() assert DateOffset(1).isAnchored() d = datetime(2008, 1, 31) assert ((d + DateOffset(months=1)) == datetime(2008, 2, 29))
Example #24
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_mul(self): assert DateOffset(2) == 2 * DateOffset(1) assert DateOffset(2) == DateOffset(1) * 2
Example #25
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_repr(self): repr(DateOffset()) repr(DateOffset(2)) repr(2 * DateOffset()) repr(2 * DateOffset(months=2))
Example #26
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_pickle_v0_15_2(self, datapath): offsets = {'DateOffset': DateOffset(years=1), 'MonthBegin': MonthBegin(1), 'Day': Day(1), 'YearBegin': YearBegin(1), 'Week': Week(1)} pickle_path = datapath('tseries', 'offsets', 'data', 'dateoffset_0_15_2.pickle') # This code was executed once on v0.15.2 to generate the pickle: # with open(pickle_path, 'wb') as f: pickle.dump(offsets, f) # tm.assert_dict_equal(offsets, read_pickle(pickle_path))
Example #27
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_rollforward(self, offset_types): expecteds = self.expecteds.copy() # result will not be changed if the target is on the offset no_changes = ['Day', 'MonthBegin', 'SemiMonthBegin', 'YearBegin', 'Week', 'Hour', 'Minute', 'Second', 'Milli', 'Micro', 'Nano', 'DateOffset'] for n in no_changes: expecteds[n] = Timestamp('2011/01/01 09:00') expecteds['BusinessHour'] = Timestamp('2011-01-03 09:00:00') expecteds['CustomBusinessHour'] = Timestamp('2011-01-03 09:00:00') # but be changed when normalize=True norm_expected = expecteds.copy() for k in norm_expected: norm_expected[k] = Timestamp(norm_expected[k].date()) normalized = {'Day': Timestamp('2011-01-02 00:00:00'), 'DateOffset': Timestamp('2011-01-02 00:00:00'), 'MonthBegin': Timestamp('2011-02-01 00:00:00'), 'SemiMonthBegin': Timestamp('2011-01-15 00:00:00'), 'YearBegin': Timestamp('2012-01-01 00:00:00'), 'Week': Timestamp('2011-01-08 00:00:00'), 'Hour': Timestamp('2011-01-01 00:00:00'), 'Minute': Timestamp('2011-01-01 00:00:00'), 'Second': Timestamp('2011-01-01 00:00:00'), 'Milli': Timestamp('2011-01-01 00:00:00'), 'Micro': Timestamp('2011-01-01 00:00:00')} norm_expected.update(normalized) sdt = datetime(2011, 1, 1, 9, 0) ndt = np_datetime64_compat('2011-01-01 09:00Z') for dt in [sdt, ndt]: expected = expecteds[offset_types.__name__] self._check_offsetfunc_works(offset_types, 'rollforward', dt, expected) expected = norm_expected[offset_types.__name__] self._check_offsetfunc_works(offset_types, 'rollforward', dt, expected, normalize=True)
Example #28
Source File: test_offsets.py From vnpy_crypto with MIT License | 5 votes |
def test_offset_freqstr(self, offset_types): offset = self._get_offset(offset_types) freqstr = offset.freqstr if freqstr not in ('<Easter>', "<DateOffset: days=1>", 'LWOM-SAT', ): code = get_offset(freqstr) assert offset.rule_code == code
Example #29
Source File: frequencies.py From Computable with MIT License | 5 votes |
def get_offset(name): """ Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1) """ if name not in _dont_uppercase: name = name.upper() if name in _rule_aliases: name = _rule_aliases[name] elif name.lower() in _rule_aliases: name = _rule_aliases[name.lower()] else: if name in _rule_aliases: name = _rule_aliases[name] if name not in _offset_map: try: # generate and cache offset offset = _make_offset(name) except (ValueError, TypeError, KeyError): # bad prefix or suffix raise ValueError('Bad rule name requested: %s.' % name) _offset_map[name] = offset return _offset_map[name]
Example #30
Source File: test_offsets.py From Computable with MIT License | 5 votes |
def test_eq(self): offset1 = DateOffset(days=1) offset2 = DateOffset(days=365) self.assert_(offset1 != offset2) self.assert_(not (offset1 == offset2))