Python dateutil.tz() Examples

The following are 30 code examples of dateutil.tz(). 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 dateutil , or try the search function .
Example #1
Source File: test_timezones.py    From recruit with Apache License 2.0 7 votes vote down vote up
def test_dti_tz_localize_nonexistent_raise_coerce(self):
        # GH#13057
        times = ['2015-03-08 01:00', '2015-03-08 02:00', '2015-03-08 03:00']
        index = DatetimeIndex(times)
        tz = 'US/Eastern'
        with pytest.raises(pytz.NonExistentTimeError):
            index.tz_localize(tz=tz)

        with pytest.raises(pytz.NonExistentTimeError):
            with tm.assert_produces_warning(FutureWarning):
                index.tz_localize(tz=tz, errors='raise')

        with tm.assert_produces_warning(FutureWarning,
                                        clear=FutureWarning,
                                        check_stacklevel=False):
            result = index.tz_localize(tz=tz, errors='coerce')
        test_times = ['2015-03-08 01:00-05:00', 'NaT',
                      '2015-03-08 03:00-04:00']
        dti = to_datetime(test_times, utc=True)
        expected = dti.tz_convert('US/Eastern')
        tm.assert_index_equal(result, expected) 
Example #2
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example #3
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_drop_dst_boundary(self):
        # see gh-18031
        tz = "Europe/Brussels"
        freq = "15min"

        start = pd.Timestamp("201710290100", tz=tz)
        end = pd.Timestamp("201710290300", tz=tz)
        index = pd.date_range(start=start, end=end, freq=freq)

        expected = DatetimeIndex(["201710290115", "201710290130",
                                  "201710290145", "201710290200",
                                  "201710290215", "201710290230",
                                  "201710290245", "201710290200",
                                  "201710290215", "201710290230",
                                  "201710290245", "201710290300"],
                                 tz=tz, freq=freq,
                                 ambiguous=[True, True, True, True,
                                            True, True, True, False,
                                            False, False, False, False])
        result = index.drop(index[0])
        tm.assert_index_equal(result, expected) 
Example #4
Source File: test_imports.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testTzAll(self):
        from dateutil.tz import tzutc
        from dateutil.tz import tzoffset
        from dateutil.tz import tzlocal
        from dateutil.tz import tzfile
        from dateutil.tz import tzrange
        from dateutil.tz import tzstr
        from dateutil.tz import tzical
        from dateutil.tz import gettz
        from dateutil.tz import tzwin
        from dateutil.tz import tzwinlocal
        from dateutil.tz import UTC
        from dateutil.tz import datetime_ambiguous
        from dateutil.tz import datetime_exists
        from dateutil.tz import resolve_imaginary

        tz_all = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange",
                  "tzstr", "tzical", "gettz", "datetime_ambiguous",
                  "datetime_exists", "resolve_imaginary", "UTC"]

        tz_all += ["tzwin", "tzwinlocal"] if sys.platform.startswith("win") else []
        lvars = locals()

        for var in tz_all:
            self.assertIsNot(lvars[var], None) 
Example #5
Source File: test_import_star.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testImportedModules(self):
        import dateutil.easter
        import dateutil.parser
        import dateutil.relativedelta
        import dateutil.rrule
        import dateutil.tz
        import dateutil.utils
        import dateutil.zoneinfo

        self.assertEquals(dateutil.easter, new_locals.pop("easter"))
        self.assertEquals(dateutil.parser, new_locals.pop("parser"))
        self.assertEquals(dateutil.relativedelta, new_locals.pop("relativedelta"))
        self.assertEquals(dateutil.rrule, new_locals.pop("rrule"))
        self.assertEquals(dateutil.tz, new_locals.pop("tz"))
        self.assertEquals(dateutil.utils, new_locals.pop("utils"))
        self.assertEquals(dateutil.zoneinfo, new_locals.pop("zoneinfo"))

        self.assertFalse(new_locals) 
Example #6
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_astype_asobject_tzinfos(self, tzstr):
        # GH#1345

        # dates around a dst transition
        rng = date_range('2/13/2010', '5/6/2010', tz=tzstr)

        objs = rng.astype(object)
        for i, x in enumerate(objs):
            exval = rng[i]
            assert x == exval
            assert x.tzinfo == exval.tzinfo

        objs = rng.astype(object)
        for i, x in enumerate(objs):
            exval = rng[i]
            assert x == exval
            assert x.tzinfo == exval.tzinfo 
Example #7
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_tz_localize_ambiguous(self):
        ts = Timestamp('2014-11-02 01:00')
        ts_dst = ts.tz_localize('US/Eastern', ambiguous=True)
        ts_no_dst = ts.tz_localize('US/Eastern', ambiguous=False)

        assert (ts_no_dst.value - ts_dst.value) / 1e9 == 3600
        with pytest.raises(ValueError):
            ts.tz_localize('US/Eastern', ambiguous='infer')

        # GH#8025
        msg = ('Cannot localize tz-aware Timestamp, '
               'use tz_convert for conversions')
        with pytest.raises(TypeError, match=msg):
            Timestamp('2011-01-01', tz='US/Eastern').tz_localize('Asia/Tokyo')

        msg = ('Cannot convert tz-naive Timestamp, '
               'use tz_localize to localize')
        with pytest.raises(TypeError, match=msg):
            Timestamp('2011-01-01').tz_convert('Asia/Tokyo') 
Example #8
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_utc_box_timestamp_and_localize(self, tzstr):
        tz = timezones.maybe_get_tz(tzstr)

        rng = date_range('3/11/2012', '3/12/2012', freq='H', tz='utc')
        rng_eastern = rng.tz_convert(tzstr)

        expected = rng[-1].astimezone(tz)

        stamp = rng_eastern[-1]
        assert stamp == expected
        assert stamp.tzinfo == expected.tzinfo

        # right tzinfo
        rng = date_range('3/13/2012', '3/14/2012', freq='H', tz='utc')
        rng_eastern = rng.tz_convert(tzstr)
        # test not valid for dateutil timezones.
        # assert 'EDT' in repr(rng_eastern[0].tzinfo)
        assert ('EDT' in repr(rng_eastern[0].tzinfo) or
                'tzfile' in repr(rng_eastern[0].tzinfo)) 
Example #9
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_tz_localize_ambiguous_infer(self, tz):
        # November 6, 2011, fall back, repeat 2 AM hour
        # With no repeated hours, we cannot infer the transition
        dr = date_range(datetime(2011, 11, 6, 0), periods=5,
                        freq=pd.offsets.Hour())
        with pytest.raises(pytz.AmbiguousTimeError):
            dr.tz_localize(tz)

        # With repeated hours, we can infer the transition
        dr = date_range(datetime(2011, 11, 6, 0), periods=5,
                        freq=pd.offsets.Hour(), tz=tz)
        times = ['11/06/2011 00:00', '11/06/2011 01:00', '11/06/2011 01:00',
                 '11/06/2011 02:00', '11/06/2011 03:00']
        di = DatetimeIndex(times)
        localized = di.tz_localize(tz, ambiguous='infer')
        tm.assert_index_equal(dr, localized)
        tm.assert_index_equal(dr, DatetimeIndex(times, tz=tz,
                                                ambiguous='infer'))

        # When there is no dst transition, nothing special happens
        dr = date_range(datetime(2011, 6, 1, 0), periods=10,
                        freq=pd.offsets.Hour())
        localized = dr.tz_localize(tz)
        localized_infer = dr.tz_localize(tz, ambiguous='infer')
        tm.assert_index_equal(localized, localized_infer) 
Example #10
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_tz_localize_ambiguous_times(self, tz):
        # March 13, 2011, spring forward, skip from 2 AM to 3 AM
        dr = date_range(datetime(2011, 3, 13, 1, 30), periods=3,
                        freq=pd.offsets.Hour())
        with pytest.raises(pytz.NonExistentTimeError):
            dr.tz_localize(tz)

        # after dst transition, it works
        dr = date_range(datetime(2011, 3, 13, 3, 30), periods=3,
                        freq=pd.offsets.Hour(), tz=tz)

        # November 6, 2011, fall back, repeat 2 AM hour
        dr = date_range(datetime(2011, 11, 6, 1, 30), periods=3,
                        freq=pd.offsets.Hour())
        with pytest.raises(pytz.AmbiguousTimeError):
            dr.tz_localize(tz)

        # UTC is OK
        dr = date_range(datetime(2011, 3, 13), periods=48,
                        freq=pd.offsets.Minute(30), tz=pytz.utc) 
Example #11
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_tz_localize(self, prefix):
        tzstr = prefix + 'US/Eastern'
        dti = pd.date_range(start='1/1/2005', end='1/1/2005 0:00:30.256',
                            freq='L')
        dti2 = dti.tz_localize(tzstr)

        dti_utc = pd.date_range(start='1/1/2005 05:00',
                                end='1/1/2005 5:00:30.256', freq='L', tz='utc')

        tm.assert_numpy_array_equal(dti2.values, dti_utc.values)

        dti3 = dti2.tz_convert(prefix + 'US/Pacific')
        tm.assert_numpy_array_equal(dti3.values, dti_utc.values)

        dti = pd.date_range(start='11/6/2011 1:59', end='11/6/2011 2:00',
                            freq='L')
        with pytest.raises(pytz.AmbiguousTimeError):
            dti.tz_localize(tzstr)

        dti = pd.date_range(start='3/13/2011 1:59', end='3/13/2011 2:00',
                            freq='L')
        with pytest.raises(pytz.NonExistentTimeError):
            dti.tz_localize(tzstr) 
Example #12
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_tz_localize_utc_conversion(self, tz):
        # Localizing to time zone should:
        #  1) check for DST ambiguities
        #  2) convert to UTC

        rng = date_range('3/10/2012', '3/11/2012', freq='30T')

        converted = rng.tz_localize(tz)
        expected_naive = rng + pd.offsets.Hour(5)
        tm.assert_numpy_array_equal(converted.asi8, expected_naive.asi8)

        # DST ambiguity, this should fail
        rng = date_range('3/11/2012', '3/12/2012', freq='30T')
        # Is this really how it should fail??
        with pytest.raises(pytz.NonExistentTimeError):
            rng.tz_localize(tz) 
Example #13
Source File: test_timezones.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = pd.date_range(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example #14
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_astype_datetime64(self):
        # GH 13149, GH 13209
        idx = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN])

        result = idx.astype('datetime64[ns]')
        tm.assert_index_equal(result, idx)
        assert result is not idx

        result = idx.astype('datetime64[ns]', copy=False)
        tm.assert_index_equal(result, idx)
        assert result is idx

        idx_tz = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN], tz='EST')
        result = idx_tz.astype('datetime64[ns]')
        expected = DatetimeIndex(['2016-05-16 05:00:00', 'NaT', 'NaT', 'NaT'],
                                 dtype='datetime64[ns]')
        tm.assert_index_equal(result, expected) 
Example #15
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_to_period_tz(self, tz):
        ts = date_range('1/1/2000', '2/1/2000', tz=tz)

        with tm.assert_produces_warning(UserWarning):
            # GH#21333 warning that timezone info will be lost
            result = ts.to_period()[0]
            expected = ts[0].to_period()

        assert result == expected

        expected = date_range('1/1/2000', '2/1/2000').to_period()

        with tm.assert_produces_warning(UserWarning):
            # GH#21333 warning that timezone info will be lost
            result = ts.to_period()

        tm.assert_index_equal(result, expected) 
Example #16
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_index_convert_to_datetime_array_dateutil(self):
        def _check_rng(rng):
            converted = rng.to_pydatetime()
            assert isinstance(converted, np.ndarray)
            for x, stamp in zip(converted, rng):
                assert isinstance(x, datetime)
                assert x == stamp.to_pydatetime()
                assert x.tzinfo == stamp.tzinfo

        rng = date_range('20090415', '20090519')
        rng_eastern = date_range('20090415', '20090519',
                                 tz='dateutil/US/Eastern')
        rng_utc = date_range('20090415', '20090519', tz=dateutil.tz.tzutc())

        _check_rng(rng)
        _check_rng(rng_eastern)
        _check_rng(rng_utc) 
Example #17
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_index_convert_to_datetime_array_explicit_pytz(self):
        def _check_rng(rng):
            converted = rng.to_pydatetime()
            assert isinstance(converted, np.ndarray)
            for x, stamp in zip(converted, rng):
                assert isinstance(x, datetime)
                assert x == stamp.to_pydatetime()
                assert x.tzinfo == stamp.tzinfo

        rng = date_range('20090415', '20090519')
        rng_eastern = date_range('20090415', '20090519',
                                 tz=pytz.timezone('US/Eastern'))
        rng_utc = date_range('20090415', '20090519', tz=pytz.utc)

        _check_rng(rng)
        _check_rng(rng_eastern)
        _check_rng(rng_utc) 
Example #18
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_index_convert_to_datetime_array(self):
        def _check_rng(rng):
            converted = rng.to_pydatetime()
            assert isinstance(converted, np.ndarray)
            for x, stamp in zip(converted, rng):
                assert isinstance(x, datetime)
                assert x == stamp.to_pydatetime()
                assert x.tzinfo == stamp.tzinfo

        rng = date_range('20090415', '20090519')
        rng_eastern = date_range('20090415', '20090519', tz='US/Eastern')
        rng_utc = date_range('20090415', '20090519', tz='utc')

        _check_rng(rng)
        _check_rng(rng_eastern)
        _check_rng(rng_utc) 
Example #19
Source File: test_astype.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_astype_with_tz(self):

        # with tz
        rng = date_range('1/1/2000', periods=10, tz='US/Eastern')
        result = rng.astype('datetime64[ns]')
        expected = (date_range('1/1/2000', periods=10,
                               tz='US/Eastern')
                    .tz_convert('UTC').tz_localize(None))
        tm.assert_index_equal(result, expected)

        # BUG#10442 : testing astype(str) is correct for Series/DatetimeIndex
        result = pd.Series(pd.date_range('2012-01-01', periods=3)).astype(str)
        expected = pd.Series(
            ['2012-01-01', '2012-01-02', '2012-01-03'], dtype=object)
        tm.assert_series_equal(result, expected)

        result = Series(pd.date_range('2012-01-01', periods=3,
                                      tz='US/Eastern')).astype(str)
        expected = Series(['2012-01-01 00:00:00-05:00',
                           '2012-01-02 00:00:00-05:00',
                           '2012-01-03 00:00:00-05:00'],
                          dtype=object)
        tm.assert_series_equal(result, expected)

        # GH 18951: tz-aware to tz-aware
        idx = date_range('20170101', periods=4, tz='US/Pacific')
        result = idx.astype('datetime64[ns, US/Eastern]')
        expected = date_range('20170101 03:00:00', periods=4, tz='US/Eastern')
        tm.assert_index_equal(result, expected)

        # GH 18951: tz-naive to tz-aware
        idx = date_range('20170101', periods=4)
        result = idx.astype('datetime64[ns, US/Eastern]')
        expected = date_range('20170101', periods=4, tz='US/Eastern')
        tm.assert_index_equal(result, expected) 
Example #20
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_iteration_preserves_nanoseconds(self, tz):
        # GH 19603
        index = DatetimeIndex(["2018-02-08 15:00:00.168456358",
                               "2018-02-08 15:00:00.168456359"], tz=tz)
        for i, ts in enumerate(index):
            assert ts == index[i] 
Example #21
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_to_datetime_utc(self):
        arr = np.array([dateutil.parser.parse('2012-06-13T01:39:00Z')],
                       dtype=object)

        result = to_datetime(arr, utc=True)
        assert result.tz is pytz.utc 
Example #22
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_hongkong_tz_convert(self):
        # GH#1673 smoke test
        dr = date_range('2012-01-01', '2012-01-10', freq='D', tz='Hongkong')

        # it works!
        dr.hour 
Example #23
Source File: test_astype.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_astype_category(self, tz):
        obj = pd.date_range("2000", periods=2, tz=tz)
        result = obj.astype('category')
        expected = pd.CategoricalIndex([pd.Timestamp('2000-01-01', tz=tz),
                                        pd.Timestamp('2000-01-02', tz=tz)])
        tm.assert_index_equal(result, expected)

        result = obj._data.astype('category')
        expected = expected.values
        tm.assert_categorical_equal(result, expected) 
Example #24
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_date_range_with_fixedoffset_noname(self):
        off = fixed_off_no_name
        start = datetime(2012, 3, 11, 5, 0, 0, tzinfo=off)
        end = datetime(2012, 6, 11, 5, 0, 0, tzinfo=off)
        rng = date_range(start=start, end=end)
        assert off == rng.tz

        idx = Index([start, end])
        assert off == idx.tz 
Example #25
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_date_range_with_tz(self, tzstr):
        stamp = Timestamp('3/11/2012 05:00', tz=tzstr)
        assert stamp.hour == 5

        rng = date_range('3/11/2012 04:00', periods=10, freq='H',
                         tz=tzstr)

        assert stamp == rng[1] 
Example #26
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_date_range_span_dst_transition(self, tzstr):
        # GH#1778

        # Standard -> Daylight Savings Time
        dr = date_range('03/06/2012 00:00', periods=200, freq='W-FRI',
                        tz='US/Eastern')

        assert (dr.hour == 0).all()

        dr = date_range('2012-11-02', periods=10, tz=tzstr)
        result = dr.hour
        expected = Index([0] * 10)
        tm.assert_index_equal(result, expected) 
Example #27
Source File: test_astype.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_astype_object_tz(self, tz):
        idx = pd.date_range(start='2013-01-01', periods=4, freq='M',
                            name='idx', tz=tz)
        expected_list = [Timestamp('2013-01-31', tz=tz),
                         Timestamp('2013-02-28', tz=tz),
                         Timestamp('2013-03-31', tz=tz),
                         Timestamp('2013-04-30', tz=tz)]
        expected = pd.Index(expected_list, dtype=object, name='idx')
        result = idx.astype(object)
        tm.assert_index_equal(result, expected)
        assert idx.tolist() == expected_list 
Example #28
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_union_aware(self):
        # non-overlapping
        rng = date_range("2012-11-15 00:00:00", periods=6, freq="H",
                         tz="US/Central")

        rng2 = date_range("2012-11-15 12:00:00", periods=6, freq="H",
                          tz="US/Eastern")

        result = rng.union(rng2)
        assert result.tz.zone == 'UTC' 
Example #29
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_convert_tz_aware_datetime_datetime(self, tz):
        # GH#1581
        dates = [datetime(2000, 1, 1), datetime(2000, 1, 2),
                 datetime(2000, 1, 3)]

        dates_aware = [conversion.localize_pydatetime(x, tz) for x in dates]
        result = DatetimeIndex(dates_aware)
        assert timezones.tz_compare(result.tz, tz)

        converted = to_datetime(dates_aware, utc=True)
        ex_vals = np.array([Timestamp(x).value for x in dates_aware])
        tm.assert_numpy_array_equal(converted.asi8, ex_vals)
        assert converted.tz is pytz.utc 
Example #30
Source File: test_timezones.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_to_datetime_fixed_offset(self):
        dates = [datetime(2000, 1, 1, tzinfo=fixed_off),
                 datetime(2000, 1, 2, tzinfo=fixed_off),
                 datetime(2000, 1, 3, tzinfo=fixed_off)]
        result = to_datetime(dates)
        assert result.tz == fixed_off