Python pandas.Timestamp() Examples

The following are 30 code examples of pandas.Timestamp(). 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 , or try the search function .
Example #1
Source File: test_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_union_sort_other_incomparable(self):
        # https://github.com/pandas-dev/pandas/issues/24959
        idx = pd.Index([1, pd.Timestamp('2000')])
        # default (sort=None)
        with tm.assert_produces_warning(RuntimeWarning):
            result = idx.union(idx[:1])

        tm.assert_index_equal(result, idx)

        # sort=None
        with tm.assert_produces_warning(RuntimeWarning):
            result = idx.union(idx[:1], sort=None)
        tm.assert_index_equal(result, idx)

        # sort=False
        result = idx.union(idx[:1], sort=False)
        tm.assert_index_equal(result, idx) 
Example #2
Source File: test_construction.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_with_timedelta64_data_deprecation(self):
        # GH#23675
        data = np.array([0], dtype='m8[ns]')
        with tm.assert_produces_warning(FutureWarning):
            result = DatetimeIndex(data)

        assert result[0] == Timestamp('1970-01-01')

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            result = to_datetime(data)

        assert result[0] == Timestamp('1970-01-01')

        with tm.assert_produces_warning(FutureWarning):
            result = DatetimeIndex(pd.TimedeltaIndex(data))

        assert result[0] == Timestamp('1970-01-01')

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            result = to_datetime(pd.TimedeltaIndex(data))

        assert result[0] == Timestamp('1970-01-01') 
Example #3
Source File: test_fixes.py    From arctic with GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_iterator(chunkstore_lib):
    """
    Fixes issue #431 - iterator methods were not taking into account
    the fact that symbols can have multiple segments
    """
    def generate_data(date):
        """
        Generates a dataframe that is larger than one segment
        a segment in chunkstore
        """
        df = pd.DataFrame(np.random.randn(200000, 12),
                          columns=['beta', 'btop', 'earnyild', 'growth', 'industry', 'leverage',
                                   'liquidty', 'momentum', 'resvol', 'sid', 'size', 'sizenl'])
        df['date'] = date

        return df

    date = pd.Timestamp('2000-01-01')
    df = generate_data(date)
    chunkstore_lib.write('test', df, chunk_size='A')
    ret = chunkstore_lib.get_chunk_ranges('test')
    assert(len(list(ret)) == 1)


# Issue 722 
Example #4
Source File: test_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_difference_incomparable(self, opname):
        a = pd.Index([3, pd.Timestamp('2000'), 1])
        b = pd.Index([2, pd.Timestamp('1999'), 1])
        op = operator.methodcaller(opname, b)

        # sort=None, the default
        result = op(a)
        expected = pd.Index([3, pd.Timestamp('2000'), 2, pd.Timestamp('1999')])
        if opname == 'difference':
            expected = expected[:2]
        tm.assert_index_equal(result, expected)

        # sort=False
        op = operator.methodcaller(opname, b, sort=False)
        result = op(a)
        tm.assert_index_equal(result, expected) 
Example #5
Source File: test_datetimes.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_fillna_preserves_tz(self, method):
        dti = pd.date_range('2000-01-01', periods=5, freq='D', tz='US/Central')
        arr = DatetimeArray(dti, copy=True)
        arr[2] = pd.NaT

        fill_val = dti[1] if method == 'pad' else dti[3]
        expected = DatetimeArray._from_sequence(
            [dti[0], dti[1], fill_val, dti[3], dti[4]],
            freq=None, tz='US/Central'
        )

        result = arr.fillna(method=method)
        tm.assert_extension_array_equal(result, expected)

        # assert that arr and dti were not modified in-place
        assert arr[2] is pd.NaT
        assert dti[2] == pd.Timestamp('2000-01-03', tz='US/Central') 
Example #6
Source File: test_datetimes.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_min_max(self, tz):
        arr = DatetimeArray._from_sequence([
            '2000-01-03',
            '2000-01-03',
            'NaT',
            '2000-01-02',
            '2000-01-05',
            '2000-01-04',
        ], tz=tz)

        result = arr.min()
        expected = pd.Timestamp('2000-01-02', tz=tz)
        assert result == expected

        result = arr.max()
        expected = pd.Timestamp('2000-01-05', tz=tz)
        assert result == expected

        result = arr.min(skipna=False)
        assert result is pd.NaT

        result = arr.max(skipna=False)
        assert result is pd.NaT 
Example #7
Source File: info.py    From xalpha with MIT License 6 votes vote down vote up
def _save_sql(self, path):
        """
        save the information and pricetable into sql, not recommend to use manually,
        just set the save label to be true when init the object

        :param path:  engine object from sqlalchemy
        """
        s = json.dumps({"name": self.name})
        df = pd.DataFrame(
            [[pd.Timestamp("1990-01-01"), 0, s, 0]],
            columns=["date", "netvalue", "comment", "totvalue"],
        )
        df = df.append(self.price, ignore_index=True, sort=True)
        df.sort_index(axis=1).to_sql(
            "xa" + self.code, con=path, if_exists="replace", index=False
        ) 
Example #8
Source File: info.py    From xalpha with MIT License 6 votes vote down vote up
def _save_sql(self, path):
        """
        save the information and pricetable into sql, not recommend to use manually,
        just set the save label to be true when init the object

        :param path:  engine object from sqlalchemy
        """
        s = json.dumps(
            {
                "feeinfo": self.feeinfo,
                "name": self.name,
                "rate": self.rate,
                "segment": self.segment,
            }
        )
        df = pd.DataFrame(
            [[pd.Timestamp("1990-01-01"), 0, s, 0]],
            columns=["date", "netvalue", "comment", "totvalue"],
        )
        df = df.append(self.price, ignore_index=True, sort=True)
        df.sort_index(axis=1).to_sql(
            "xa" + self.code, con=path, if_exists="replace", index=False
        ) 
Example #9
Source File: test_recorders.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
def test_seasonal_fdc_recorder(self):
        """
        Test the FlowDurationCurveRecorder
        """
        model = load_model("timeseries4.json")

        df = pandas.read_csv(os.path.join(os.path.dirname(__file__), 'models', 'timeseries3.csv'),
                             parse_dates=True, dayfirst=True, index_col=0)

        percentiles = np.linspace(20., 100., 5)

        summer_flows = df.loc[pandas.Timestamp("2014-06-01"):pandas.Timestamp("2014-08-31"), :]
        summer_fdc = np.percentile(summer_flows, percentiles, axis=0)

        model.run()

        rec = model.recorders["seasonal_fdc"]
        assert_allclose(rec.fdc, summer_fdc) 
Example #10
Source File: test_datetimelike.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_take_fill(self):
        data = np.arange(10, dtype='i8') * 24 * 3600 * 10**9

        idx = self.index_cls._simple_new(data, freq='D')
        arr = self.array_cls(idx)

        result = arr.take([-1, 1], allow_fill=True, fill_value=None)
        assert result[0] is pd.NaT

        result = arr.take([-1, 1], allow_fill=True, fill_value=np.nan)
        assert result[0] is pd.NaT

        result = arr.take([-1, 1], allow_fill=True, fill_value=pd.NaT)
        assert result[0] is pd.NaT

        with pytest.raises(ValueError):
            arr.take([0, 1], allow_fill=True, fill_value=2)

        with pytest.raises(ValueError):
            arr.take([0, 1], allow_fill=True, fill_value=2.0)

        with pytest.raises(ValueError):
            arr.take([0, 1], allow_fill=True,
                     fill_value=pd.Timestamp.now().time) 
Example #11
Source File: test_datetimelike.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_take_fill_valid(self, timedelta_index):
        tdi = timedelta_index
        arr = TimedeltaArray(tdi)

        td1 = pd.Timedelta(days=1)
        result = arr.take([-1, 1], allow_fill=True, fill_value=td1)
        assert result[0] == td1

        now = pd.Timestamp.now()
        with pytest.raises(ValueError):
            # fill_value Timestamp invalid
            arr.take([0, 1], allow_fill=True, fill_value=now)

        with pytest.raises(ValueError):
            # fill_value Period invalid
            arr.take([0, 1], allow_fill=True, fill_value=now.to_period('D')) 
Example #12
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_construction_ambiguous_endpoint(self, tz):
        # construction with an ambiguous end-point
        # GH#11626

        # FIXME: This next block fails to raise; it was taken from an older
        # version of this test that had an indention mistake that caused it
        # to not get executed.
        # with pytest.raises(pytz.AmbiguousTimeError):
        #    date_range("2013-10-26 23:00", "2013-10-27 01:00",
        #               tz="Europe/London", freq="H")

        times = date_range("2013-10-26 23:00", "2013-10-27 01:00", freq="H",
                           tz=tz, ambiguous='infer')
        assert times[0] == Timestamp('2013-10-26 23:00', tz=tz, freq="H")

        if str(tz).startswith('dateutil'):
            if LooseVersion(dateutil.__version__) < LooseVersion('2.6.0'):
                # see GH#14621
                assert times[-1] == Timestamp('2013-10-27 01:00:00+0000',
                                              tz=tz, freq="H")
            elif LooseVersion(dateutil.__version__) > LooseVersion('2.6.0'):
                # fixed ambiguous behavior
                assert times[-1] == Timestamp('2013-10-27 01:00:00+0100',
                                              tz=tz, freq="H")
        else:
            assert times[-1] == Timestamp('2013-10-27 01:00:00+0000',
                                          tz=tz, freq="H") 
Example #13
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_format(self):
        self._check_method_works(Index.format)

        # GH 14626
        # windows has different precision on datetime.datetime.now (it doesn't
        # include us since the default for Timestamp shows these but Index
        # formatting does not we are skipping)
        now = datetime.now()
        if not str(now).endswith("000"):
            index = Index([now])
            formatted = index.format()
            expected = [str(index[0])]
            assert formatted == expected

        self.strIndex[:0].format() 
Example #14
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_tz_localize_nonexistent_shift(self, start_ts, tz,
                                               end_ts, shift,
                                               tz_type):
        # GH 8917
        tz = tz_type + tz
        if isinstance(shift, str):
            shift = 'shift_' + shift
        dti = DatetimeIndex([Timestamp(start_ts)])
        result = dti.tz_localize(tz, nonexistent=shift)
        expected = DatetimeIndex([Timestamp(end_ts)]).tz_localize(tz)
        tm.assert_index_equal(result, expected) 
Example #15
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_tz_convert_hour_overflow_dst_timestamps(self, tz):
        # Regression test for GH#13306

        # sorted case US/Eastern -> UTC
        ts = [Timestamp('2008-05-12 09:50:00', tz=tz),
              Timestamp('2008-12-12 09:50:35', tz=tz),
              Timestamp('2009-05-12 09:50:32', tz=tz)]
        tt = DatetimeIndex(ts)
        ut = tt.tz_convert('UTC')
        expected = Index([13, 14, 13])
        tm.assert_index_equal(ut.hour, expected)

        # sorted case UTC -> US/Eastern
        ts = [Timestamp('2008-05-12 13:50:00', tz='UTC'),
              Timestamp('2008-12-12 14:50:35', tz='UTC'),
              Timestamp('2009-05-12 13:50:32', tz='UTC')]
        tt = DatetimeIndex(ts)
        ut = tt.tz_convert('US/Eastern')
        expected = Index([9, 9, 9])
        tm.assert_index_equal(ut.hour, expected)

        # unsorted case US/Eastern -> UTC
        ts = [Timestamp('2008-05-12 09:50:00', tz=tz),
              Timestamp('2008-12-12 09:50:35', tz=tz),
              Timestamp('2008-05-12 09:50:32', tz=tz)]
        tt = DatetimeIndex(ts)
        ut = tt.tz_convert('UTC')
        expected = Index([13, 14, 13])
        tm.assert_index_equal(ut.hour, expected)

        # unsorted case UTC -> US/Eastern
        ts = [Timestamp('2008-05-12 13:50:00', tz='UTC'),
              Timestamp('2008-12-12 14:50:35', tz='UTC'),
              Timestamp('2008-05-12 13:50:32', tz='UTC')]
        tt = DatetimeIndex(ts)
        ut = tt.tz_convert('US/Eastern')
        expected = Index([9, 9, 9])
        tm.assert_index_equal(ut.hour, expected) 
Example #16
Source File: test_construction.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_construction_with_nat_and_tzlocal(self):
        tz = dateutil.tz.tzlocal()
        result = DatetimeIndex(['2018', 'NaT'], tz=tz)
        expected = DatetimeIndex([Timestamp('2018', tz=tz), pd.NaT])
        tm.assert_index_equal(result, expected) 
Example #17
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_tz_localize_nonexistent_shift_invalid(self, offset, tz_type):
        # GH 8917
        tz = tz_type + 'Europe/Warsaw'
        dti = DatetimeIndex([Timestamp('2015-03-29 02:20:00')])
        msg = "The provided timedelta will relocalize on a nonexistent time"
        with pytest.raises(ValueError, match=msg):
            dti.tz_localize(tz, nonexistent=timedelta(seconds=offset)) 
Example #18
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_hour(self):
        dr = date_range(start=Timestamp('2000-02-27'), periods=5, freq='H')
        r1 = pd.Index([x.to_julian_date() for x in dr])
        r2 = dr.to_julian_date()
        assert isinstance(r2, pd.Float64Index)
        tm.assert_index_equal(r1, r2) 
Example #19
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_2000(self):
        dr = date_range(start=Timestamp('2000-02-27'), periods=5, freq='D')
        r1 = pd.Index([x.to_julian_date() for x in dr])
        r2 = dr.to_julian_date()
        assert isinstance(r2, pd.Float64Index)
        tm.assert_index_equal(r1, r2) 
Example #20
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_normalize_nat(self):
        dti = DatetimeIndex([pd.NaT, Timestamp('2018-01-01 01:00:00')])
        result = dti.normalize()
        expected = DatetimeIndex([pd.NaT, Timestamp('2018-01-01')])
        tm.assert_index_equal(result, expected) 
Example #21
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_tz_nat(self, tzstr):
        idx = DatetimeIndex([Timestamp("2013-1-1", tz=tzstr), pd.NaT])

        assert isna(idx[1])
        assert idx[0].tzinfo is not None 
Example #22
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_no_rounding_occurs(self, tz_naive_fixture):
        # GH 21262
        tz = tz_naive_fixture
        rng = date_range(start='2016-01-01', periods=5,
                         freq='2Min', tz=tz)

        expected_rng = DatetimeIndex([
            Timestamp('2016-01-01 00:00:00', tz=tz, freq='2T'),
            Timestamp('2016-01-01 00:02:00', tz=tz, freq='2T'),
            Timestamp('2016-01-01 00:04:00', tz=tz, freq='2T'),
            Timestamp('2016-01-01 00:06:00', tz=tz, freq='2T'),
            Timestamp('2016-01-01 00:08:00', tz=tz, freq='2T'),
        ])

        tm.assert_index_equal(rng.round(freq='2T'), expected_rng) 
Example #23
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_timestamp_freq_fields(self):
        # extra fields from DatetimeIndex like quarter and week
        idx = tm.makeDateIndex(100)

        assert idx.freq == Timestamp(idx[-1], idx.freq).freq
        assert idx.freqstr == Timestamp(idx[-1], idx.freq).freqstr

    # ----------------------------------------------------------------
    # DatetimeIndex.round 
Example #24
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_timestamp_fields(self, field):
        # extra fields from DatetimeIndex like quarter and week
        idx = tm.makeDateIndex(100)
        expected = getattr(idx, field)[-1]
        if field == 'weekday_name':
            with tm.assert_produces_warning(FutureWarning,
                                            check_stacklevel=False):
                result = getattr(Timestamp(idx[-1]), field)
        else:
            result = getattr(Timestamp(idx[-1]), field)
        assert result == expected 
Example #25
Source File: test_construction.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_freq_validation_with_nat(self, dt_cls):
        # GH#11587 make sure we get a useful error message when generate_range
        #  raises
        msg = ("Inferred frequency None from passed values does not conform "
               "to passed frequency D")
        with pytest.raises(ValueError, match=msg):
            dt_cls([pd.NaT, pd.Timestamp('2011-01-01')], freq='D')
        with pytest.raises(ValueError, match=msg):
            dt_cls([pd.NaT, pd.Timestamp('2011-01-01').value],
                   freq='D') 
Example #26
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_difference_incomparable_true(self, opname):
        # TODO decide on True behaviour
        # # sort=True, raises
        a = pd.Index([3, pd.Timestamp('2000'), 1])
        b = pd.Index([2, pd.Timestamp('1999'), 1])
        op = operator.methodcaller(opname, b, sort=True)

        with pytest.raises(TypeError, match='Cannot compare'):
            op(a) 
Example #27
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_union_sort_other_incomparable_true(self):
        # TODO decide on True behaviour
        # sort=True
        idx = pd.Index([1, pd.Timestamp('2000')])
        with pytest.raises(TypeError, match='.*'):
            idx.union(idx[:1], sort=True) 
Example #28
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_asof_datetime_partial(self):
        index = pd.date_range('2010-01-01', periods=2, freq='m')
        expected = Timestamp('2010-02-28')
        result = index.asof('2010-02')
        assert result == expected
        assert not isinstance(result, Index) 
Example #29
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_asof(self):
        d = self.dateIndex[0]
        assert self.dateIndex.asof(d) == d
        assert isna(self.dateIndex.asof(d - timedelta(1)))

        d = self.dateIndex[-1]
        assert self.dateIndex.asof(d + timedelta(1)) == d

        d = self.dateIndex[0].to_pydatetime()
        assert isinstance(self.dateIndex.asof(d), Timestamp) 
Example #30
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_constructor_from_series(self, klass):
        expected = DatetimeIndex([Timestamp('20110101'), Timestamp('20120101'),
                                  Timestamp('20130101')])
        s = Series([Timestamp('20110101'), Timestamp('20120101'),
                    Timestamp('20130101')])
        result = klass(s)
        tm.assert_index_equal(result, expected)