demo + utils venv
This commit is contained in:
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+117
@@ -0,0 +1,117 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from pandas.compat import long
|
||||
|
||||
from pandas import Timedelta, Timestamp
|
||||
import pandas.util.testing as tm
|
||||
|
||||
from pandas.tseries import offsets
|
||||
from pandas.tseries.frequencies import to_offset
|
||||
|
||||
|
||||
class TestTimestampArithmetic(object):
|
||||
def test_overflow_offset(self):
|
||||
# no overflow expected
|
||||
|
||||
stamp = Timestamp("2000/1/1")
|
||||
offset_no_overflow = to_offset("D") * 100
|
||||
|
||||
expected = Timestamp("2000/04/10")
|
||||
assert stamp + offset_no_overflow == expected
|
||||
|
||||
assert offset_no_overflow + stamp == expected
|
||||
|
||||
expected = Timestamp("1999/09/23")
|
||||
assert stamp - offset_no_overflow == expected
|
||||
|
||||
def test_overflow_offset_raises(self):
|
||||
# xref https://github.com/statsmodels/statsmodels/issues/3374
|
||||
# ends up multiplying really large numbers which overflow
|
||||
|
||||
stamp = Timestamp('2017-01-13 00:00:00', freq='D')
|
||||
offset_overflow = 20169940 * offsets.Day(1)
|
||||
msg = ("the add operation between "
|
||||
r"\<-?\d+ \* Days\> and \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} "
|
||||
"will overflow")
|
||||
|
||||
with pytest.raises(OverflowError, match=msg):
|
||||
stamp + offset_overflow
|
||||
|
||||
with pytest.raises(OverflowError, match=msg):
|
||||
offset_overflow + stamp
|
||||
|
||||
with pytest.raises(OverflowError, match=msg):
|
||||
stamp - offset_overflow
|
||||
|
||||
# xref https://github.com/pandas-dev/pandas/issues/14080
|
||||
# used to crash, so check for proper overflow exception
|
||||
|
||||
stamp = Timestamp("2000/1/1")
|
||||
offset_overflow = to_offset("D") * 100 ** 25
|
||||
|
||||
with pytest.raises(OverflowError, match=msg):
|
||||
stamp + offset_overflow
|
||||
|
||||
with pytest.raises(OverflowError, match=msg):
|
||||
offset_overflow + stamp
|
||||
|
||||
with pytest.raises(OverflowError, match=msg):
|
||||
stamp - offset_overflow
|
||||
|
||||
def test_delta_preserve_nanos(self):
|
||||
val = Timestamp(long(1337299200000000123))
|
||||
result = val + timedelta(1)
|
||||
assert result.nanosecond == val.nanosecond
|
||||
|
||||
def test_timestamp_sub_datetime(self):
|
||||
dt = datetime(2013, 10, 12)
|
||||
ts = Timestamp(datetime(2013, 10, 13))
|
||||
assert (ts - dt).days == 1
|
||||
assert (dt - ts).days == -1
|
||||
|
||||
def test_addition_subtraction_types(self):
|
||||
# Assert on the types resulting from Timestamp +/- various date/time
|
||||
# objects
|
||||
dt = datetime(2014, 3, 4)
|
||||
td = timedelta(seconds=1)
|
||||
# build a timestamp with a frequency, since then it supports
|
||||
# addition/subtraction of integers
|
||||
ts = Timestamp(dt, freq='D')
|
||||
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
# GH#22535 add/sub with integers is deprecated
|
||||
assert type(ts + 1) == Timestamp
|
||||
assert type(ts - 1) == Timestamp
|
||||
|
||||
# Timestamp + datetime not supported, though subtraction is supported
|
||||
# and yields timedelta more tests in tseries/base/tests/test_base.py
|
||||
assert type(ts - dt) == Timedelta
|
||||
assert type(ts + td) == Timestamp
|
||||
assert type(ts - td) == Timestamp
|
||||
|
||||
# Timestamp +/- datetime64 not supported, so not tested (could possibly
|
||||
# assert error raised?)
|
||||
td64 = np.timedelta64(1, 'D')
|
||||
assert type(ts + td64) == Timestamp
|
||||
assert type(ts - td64) == Timestamp
|
||||
|
||||
def test_addition_subtraction_preserve_frequency(self):
|
||||
ts = Timestamp('2014-03-05', freq='D')
|
||||
td = timedelta(days=1)
|
||||
original_freq = ts.freq
|
||||
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
# GH#22535 add/sub with integers is deprecated
|
||||
assert (ts + 1).freq == original_freq
|
||||
assert (ts - 1).freq == original_freq
|
||||
|
||||
assert (ts + td).freq == original_freq
|
||||
assert (ts - td).freq == original_freq
|
||||
|
||||
td64 = np.timedelta64(1, 'D')
|
||||
assert (ts + td64).freq == original_freq
|
||||
assert (ts - td64).freq == original_freq
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from datetime import datetime
|
||||
import operator
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from pandas.compat import PY2, long
|
||||
|
||||
from pandas import Timestamp
|
||||
|
||||
|
||||
class TestTimestampComparison(object):
|
||||
def test_comparison_object_array(self):
|
||||
# GH#15183
|
||||
ts = Timestamp('2011-01-03 00:00:00-0500', tz='US/Eastern')
|
||||
other = Timestamp('2011-01-01 00:00:00-0500', tz='US/Eastern')
|
||||
naive = Timestamp('2011-01-01 00:00:00')
|
||||
|
||||
arr = np.array([other, ts], dtype=object)
|
||||
res = arr == ts
|
||||
expected = np.array([False, True], dtype=bool)
|
||||
assert (res == expected).all()
|
||||
|
||||
# 2D case
|
||||
arr = np.array([[other, ts],
|
||||
[ts, other]],
|
||||
dtype=object)
|
||||
res = arr != ts
|
||||
expected = np.array([[True, False], [False, True]], dtype=bool)
|
||||
assert res.shape == expected.shape
|
||||
assert (res == expected).all()
|
||||
|
||||
# tzaware mismatch
|
||||
arr = np.array([naive], dtype=object)
|
||||
with pytest.raises(TypeError):
|
||||
arr < ts
|
||||
|
||||
def test_comparison(self):
|
||||
# 5-18-2012 00:00:00.000
|
||||
stamp = long(1337299200000000000)
|
||||
|
||||
val = Timestamp(stamp)
|
||||
|
||||
assert val == val
|
||||
assert not val != val
|
||||
assert not val < val
|
||||
assert val <= val
|
||||
assert not val > val
|
||||
assert val >= val
|
||||
|
||||
other = datetime(2012, 5, 18)
|
||||
assert val == other
|
||||
assert not val != other
|
||||
assert not val < other
|
||||
assert val <= other
|
||||
assert not val > other
|
||||
assert val >= other
|
||||
|
||||
other = Timestamp(stamp + 100)
|
||||
|
||||
assert val != other
|
||||
assert val != other
|
||||
assert val < other
|
||||
assert val <= other
|
||||
assert other > val
|
||||
assert other >= val
|
||||
|
||||
def test_compare_invalid(self):
|
||||
# GH#8058
|
||||
val = Timestamp('20130101 12:01:02')
|
||||
assert not val == 'foo'
|
||||
assert not val == 10.0
|
||||
assert not val == 1
|
||||
assert not val == long(1)
|
||||
assert not val == []
|
||||
assert not val == {'foo': 1}
|
||||
assert not val == np.float64(1)
|
||||
assert not val == np.int64(1)
|
||||
|
||||
assert val != 'foo'
|
||||
assert val != 10.0
|
||||
assert val != 1
|
||||
assert val != long(1)
|
||||
assert val != []
|
||||
assert val != {'foo': 1}
|
||||
assert val != np.float64(1)
|
||||
assert val != np.int64(1)
|
||||
|
||||
def test_cant_compare_tz_naive_w_aware(self, utc_fixture):
|
||||
# see GH#1404
|
||||
a = Timestamp('3/12/2012')
|
||||
b = Timestamp('3/12/2012', tz=utc_fixture)
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
a == b
|
||||
with pytest.raises(TypeError):
|
||||
a != b
|
||||
with pytest.raises(TypeError):
|
||||
a < b
|
||||
with pytest.raises(TypeError):
|
||||
a <= b
|
||||
with pytest.raises(TypeError):
|
||||
a > b
|
||||
with pytest.raises(TypeError):
|
||||
a >= b
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
b == a
|
||||
with pytest.raises(TypeError):
|
||||
b != a
|
||||
with pytest.raises(TypeError):
|
||||
b < a
|
||||
with pytest.raises(TypeError):
|
||||
b <= a
|
||||
with pytest.raises(TypeError):
|
||||
b > a
|
||||
with pytest.raises(TypeError):
|
||||
b >= a
|
||||
|
||||
if PY2:
|
||||
with pytest.raises(TypeError):
|
||||
a == b.to_pydatetime()
|
||||
with pytest.raises(TypeError):
|
||||
a.to_pydatetime() == b
|
||||
else:
|
||||
assert not a == b.to_pydatetime()
|
||||
assert not a.to_pydatetime() == b
|
||||
|
||||
def test_timestamp_compare_scalars(self):
|
||||
# case where ndim == 0
|
||||
lhs = np.datetime64(datetime(2013, 12, 6))
|
||||
rhs = Timestamp('now')
|
||||
nat = Timestamp('nat')
|
||||
|
||||
ops = {'gt': 'lt',
|
||||
'lt': 'gt',
|
||||
'ge': 'le',
|
||||
'le': 'ge',
|
||||
'eq': 'eq',
|
||||
'ne': 'ne'}
|
||||
|
||||
for left, right in ops.items():
|
||||
left_f = getattr(operator, left)
|
||||
right_f = getattr(operator, right)
|
||||
expected = left_f(lhs, rhs)
|
||||
|
||||
result = right_f(rhs, lhs)
|
||||
assert result == expected
|
||||
|
||||
expected = left_f(rhs, nat)
|
||||
result = right_f(nat, rhs)
|
||||
assert result == expected
|
||||
|
||||
def test_timestamp_compare_with_early_datetime(self):
|
||||
# e.g. datetime.min
|
||||
stamp = Timestamp('2012-01-01')
|
||||
|
||||
assert not stamp == datetime.min
|
||||
assert not stamp == datetime(1600, 1, 1)
|
||||
assert not stamp == datetime(2700, 1, 1)
|
||||
assert stamp != datetime.min
|
||||
assert stamp != datetime(1600, 1, 1)
|
||||
assert stamp != datetime(2700, 1, 1)
|
||||
assert stamp > datetime(1600, 1, 1)
|
||||
assert stamp >= datetime(1600, 1, 1)
|
||||
assert stamp < datetime(2700, 1, 1)
|
||||
assert stamp <= datetime(2700, 1, 1)
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from distutils.version import LooseVersion
|
||||
import pprint
|
||||
|
||||
import dateutil
|
||||
import pytest
|
||||
import pytz # noqa # a test below uses pytz but only inside a `eval` call
|
||||
|
||||
from pandas import Timestamp
|
||||
|
||||
|
||||
class TestTimestampRendering(object):
|
||||
|
||||
# dateutil zone change (only matters for repr)
|
||||
if LooseVersion(dateutil.__version__) >= LooseVersion('2.6.0'):
|
||||
timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern',
|
||||
'dateutil/US/Pacific']
|
||||
else:
|
||||
timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern',
|
||||
'dateutil/America/Los_Angeles']
|
||||
|
||||
@pytest.mark.parametrize('tz', timezones)
|
||||
@pytest.mark.parametrize('freq', ['D', 'M', 'S', 'N'])
|
||||
@pytest.mark.parametrize('date', ['2014-03-07', '2014-01-01 09:00',
|
||||
'2014-01-01 00:00:00.000000001'])
|
||||
def test_repr(self, date, freq, tz):
|
||||
# avoid to match with timezone name
|
||||
freq_repr = "'{0}'".format(freq)
|
||||
if tz.startswith('dateutil'):
|
||||
tz_repr = tz.replace('dateutil', '')
|
||||
else:
|
||||
tz_repr = tz
|
||||
|
||||
date_only = Timestamp(date)
|
||||
assert date in repr(date_only)
|
||||
assert tz_repr not in repr(date_only)
|
||||
assert freq_repr not in repr(date_only)
|
||||
assert date_only == eval(repr(date_only))
|
||||
|
||||
date_tz = Timestamp(date, tz=tz)
|
||||
assert date in repr(date_tz)
|
||||
assert tz_repr in repr(date_tz)
|
||||
assert freq_repr not in repr(date_tz)
|
||||
assert date_tz == eval(repr(date_tz))
|
||||
|
||||
date_freq = Timestamp(date, freq=freq)
|
||||
assert date in repr(date_freq)
|
||||
assert tz_repr not in repr(date_freq)
|
||||
assert freq_repr in repr(date_freq)
|
||||
assert date_freq == eval(repr(date_freq))
|
||||
|
||||
date_tz_freq = Timestamp(date, tz=tz, freq=freq)
|
||||
assert date in repr(date_tz_freq)
|
||||
assert tz_repr in repr(date_tz_freq)
|
||||
assert freq_repr in repr(date_tz_freq)
|
||||
assert date_tz_freq == eval(repr(date_tz_freq))
|
||||
|
||||
def test_repr_utcoffset(self):
|
||||
# This can cause the tz field to be populated, but it's redundant to
|
||||
# include this information in the date-string.
|
||||
date_with_utc_offset = Timestamp('2014-03-13 00:00:00-0400', tz=None)
|
||||
assert '2014-03-13 00:00:00-0400' in repr(date_with_utc_offset)
|
||||
assert 'tzoffset' not in repr(date_with_utc_offset)
|
||||
assert 'pytz.FixedOffset(-240)' in repr(date_with_utc_offset)
|
||||
expr = repr(date_with_utc_offset).replace("'pytz.FixedOffset(-240)'",
|
||||
'pytz.FixedOffset(-240)')
|
||||
assert date_with_utc_offset == eval(expr)
|
||||
|
||||
def test_timestamp_repr_pre1900(self):
|
||||
# pre-1900
|
||||
stamp = Timestamp('1850-01-01', tz='US/Eastern')
|
||||
repr(stamp)
|
||||
|
||||
iso8601 = '1850-01-01 01:23:45.012345'
|
||||
stamp = Timestamp(iso8601, tz='US/Eastern')
|
||||
result = repr(stamp)
|
||||
assert iso8601 in result
|
||||
|
||||
def test_pprint(self):
|
||||
# GH#12622
|
||||
nested_obj = {'foo': 1,
|
||||
'bar': [{'w': {'a': Timestamp('2011-01-01')}}] * 10}
|
||||
result = pprint.pformat(nested_obj, width=50)
|
||||
expected = r"""{'bar': [{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
|
||||
{'w': {'a': Timestamp('2011-01-01 00:00:00')}}],
|
||||
'foo': 1}"""
|
||||
assert result == expected
|
||||
+964
@@ -0,0 +1,964 @@
|
||||
""" test the scalar Timestamp """
|
||||
|
||||
import calendar
|
||||
from datetime import datetime, timedelta
|
||||
import locale
|
||||
import unicodedata
|
||||
|
||||
import dateutil
|
||||
from dateutil.tz import tzutc
|
||||
import numpy as np
|
||||
import pytest
|
||||
import pytz
|
||||
from pytz import timezone, utc
|
||||
|
||||
from pandas._libs.tslibs import conversion
|
||||
from pandas._libs.tslibs.timezones import dateutil_gettz as gettz, get_timezone
|
||||
from pandas.compat import PY2, PY3, long
|
||||
from pandas.compat.numpy import np_datetime64_compat
|
||||
from pandas.errors import OutOfBoundsDatetime
|
||||
import pandas.util._test_decorators as td
|
||||
|
||||
from pandas import NaT, Period, Timedelta, Timestamp
|
||||
import pandas.util.testing as tm
|
||||
|
||||
from pandas.tseries import offsets
|
||||
|
||||
|
||||
class TestTimestampProperties(object):
|
||||
|
||||
def test_properties_business(self):
|
||||
ts = Timestamp('2017-10-01', freq='B')
|
||||
control = Timestamp('2017-10-01')
|
||||
assert ts.dayofweek == 6
|
||||
assert not ts.is_month_start # not a weekday
|
||||
assert not ts.is_quarter_start # not a weekday
|
||||
# Control case: non-business is month/qtr start
|
||||
assert control.is_month_start
|
||||
assert control.is_quarter_start
|
||||
|
||||
ts = Timestamp('2017-09-30', freq='B')
|
||||
control = Timestamp('2017-09-30')
|
||||
assert ts.dayofweek == 5
|
||||
assert not ts.is_month_end # not a weekday
|
||||
assert not ts.is_quarter_end # not a weekday
|
||||
# Control case: non-business is month/qtr start
|
||||
assert control.is_month_end
|
||||
assert control.is_quarter_end
|
||||
|
||||
def test_fields(self):
|
||||
def check(value, equal):
|
||||
# that we are int/long like
|
||||
assert isinstance(value, (int, long))
|
||||
assert value == equal
|
||||
|
||||
# GH 10050
|
||||
ts = Timestamp('2015-05-10 09:06:03.000100001')
|
||||
check(ts.year, 2015)
|
||||
check(ts.month, 5)
|
||||
check(ts.day, 10)
|
||||
check(ts.hour, 9)
|
||||
check(ts.minute, 6)
|
||||
check(ts.second, 3)
|
||||
pytest.raises(AttributeError, lambda: ts.millisecond)
|
||||
check(ts.microsecond, 100)
|
||||
check(ts.nanosecond, 1)
|
||||
check(ts.dayofweek, 6)
|
||||
check(ts.quarter, 2)
|
||||
check(ts.dayofyear, 130)
|
||||
check(ts.week, 19)
|
||||
check(ts.daysinmonth, 31)
|
||||
check(ts.daysinmonth, 31)
|
||||
|
||||
# GH 13303
|
||||
ts = Timestamp('2014-12-31 23:59:00-05:00', tz='US/Eastern')
|
||||
check(ts.year, 2014)
|
||||
check(ts.month, 12)
|
||||
check(ts.day, 31)
|
||||
check(ts.hour, 23)
|
||||
check(ts.minute, 59)
|
||||
check(ts.second, 0)
|
||||
pytest.raises(AttributeError, lambda: ts.millisecond)
|
||||
check(ts.microsecond, 0)
|
||||
check(ts.nanosecond, 0)
|
||||
check(ts.dayofweek, 2)
|
||||
check(ts.quarter, 4)
|
||||
check(ts.dayofyear, 365)
|
||||
check(ts.week, 1)
|
||||
check(ts.daysinmonth, 31)
|
||||
|
||||
ts = Timestamp('2014-01-01 00:00:00+01:00')
|
||||
starts = ['is_month_start', 'is_quarter_start', 'is_year_start']
|
||||
for start in starts:
|
||||
assert getattr(ts, start)
|
||||
ts = Timestamp('2014-12-31 23:59:59+01:00')
|
||||
ends = ['is_month_end', 'is_year_end', 'is_quarter_end']
|
||||
for end in ends:
|
||||
assert getattr(ts, end)
|
||||
|
||||
# GH 12806
|
||||
@pytest.mark.parametrize('data',
|
||||
[Timestamp('2017-08-28 23:00:00'),
|
||||
Timestamp('2017-08-28 23:00:00', tz='EST')])
|
||||
@pytest.mark.parametrize('time_locale', [
|
||||
None] if tm.get_locales() is None else [None] + tm.get_locales())
|
||||
def test_names(self, data, time_locale):
|
||||
# GH 17354
|
||||
# Test .weekday_name, .day_name(), .month_name
|
||||
with tm.assert_produces_warning(FutureWarning,
|
||||
check_stacklevel=False):
|
||||
assert data.weekday_name == 'Monday'
|
||||
if time_locale is None:
|
||||
expected_day = 'Monday'
|
||||
expected_month = 'August'
|
||||
else:
|
||||
with tm.set_locale(time_locale, locale.LC_TIME):
|
||||
expected_day = calendar.day_name[0].capitalize()
|
||||
expected_month = calendar.month_name[8].capitalize()
|
||||
|
||||
result_day = data.day_name(time_locale)
|
||||
result_month = data.month_name(time_locale)
|
||||
|
||||
# Work around https://github.com/pandas-dev/pandas/issues/22342
|
||||
# different normalizations
|
||||
|
||||
if not PY2:
|
||||
expected_day = unicodedata.normalize("NFD", expected_day)
|
||||
expected_month = unicodedata.normalize("NFD", expected_month)
|
||||
|
||||
result_day = unicodedata.normalize("NFD", result_day,)
|
||||
result_month = unicodedata.normalize("NFD", result_month)
|
||||
|
||||
assert result_day == expected_day
|
||||
assert result_month == expected_month
|
||||
|
||||
# Test NaT
|
||||
nan_ts = Timestamp(NaT)
|
||||
assert np.isnan(nan_ts.day_name(time_locale))
|
||||
assert np.isnan(nan_ts.month_name(time_locale))
|
||||
|
||||
def test_is_leap_year(self, tz_naive_fixture):
|
||||
tz = tz_naive_fixture
|
||||
# GH 13727
|
||||
dt = Timestamp('2000-01-01 00:00:00', tz=tz)
|
||||
assert dt.is_leap_year
|
||||
assert isinstance(dt.is_leap_year, bool)
|
||||
|
||||
dt = Timestamp('1999-01-01 00:00:00', tz=tz)
|
||||
assert not dt.is_leap_year
|
||||
|
||||
dt = Timestamp('2004-01-01 00:00:00', tz=tz)
|
||||
assert dt.is_leap_year
|
||||
|
||||
dt = Timestamp('2100-01-01 00:00:00', tz=tz)
|
||||
assert not dt.is_leap_year
|
||||
|
||||
def test_woy_boundary(self):
|
||||
# make sure weeks at year boundaries are correct
|
||||
d = datetime(2013, 12, 31)
|
||||
result = Timestamp(d).week
|
||||
expected = 1 # ISO standard
|
||||
assert result == expected
|
||||
|
||||
d = datetime(2008, 12, 28)
|
||||
result = Timestamp(d).week
|
||||
expected = 52 # ISO standard
|
||||
assert result == expected
|
||||
|
||||
d = datetime(2009, 12, 31)
|
||||
result = Timestamp(d).week
|
||||
expected = 53 # ISO standard
|
||||
assert result == expected
|
||||
|
||||
d = datetime(2010, 1, 1)
|
||||
result = Timestamp(d).week
|
||||
expected = 53 # ISO standard
|
||||
assert result == expected
|
||||
|
||||
d = datetime(2010, 1, 3)
|
||||
result = Timestamp(d).week
|
||||
expected = 53 # ISO standard
|
||||
assert result == expected
|
||||
|
||||
result = np.array([Timestamp(datetime(*args)).week
|
||||
for args in [(2000, 1, 1), (2000, 1, 2), (
|
||||
2005, 1, 1), (2005, 1, 2)]])
|
||||
assert (result == [52, 52, 53, 53]).all()
|
||||
|
||||
def test_resolution(self):
|
||||
# GH#21336, GH#21365
|
||||
dt = Timestamp('2100-01-01 00:00:00')
|
||||
assert dt.resolution == Timedelta(nanoseconds=1)
|
||||
|
||||
|
||||
class TestTimestampConstructors(object):
|
||||
|
||||
def test_constructor(self):
|
||||
base_str = '2014-07-01 09:00'
|
||||
base_dt = datetime(2014, 7, 1, 9)
|
||||
base_expected = 1404205200000000000
|
||||
|
||||
# confirm base representation is correct
|
||||
import calendar
|
||||
assert (calendar.timegm(base_dt.timetuple()) * 1000000000 ==
|
||||
base_expected)
|
||||
|
||||
tests = [(base_str, base_dt, base_expected),
|
||||
('2014-07-01 10:00', datetime(2014, 7, 1, 10),
|
||||
base_expected + 3600 * 1000000000),
|
||||
('2014-07-01 09:00:00.000008000',
|
||||
datetime(2014, 7, 1, 9, 0, 0, 8),
|
||||
base_expected + 8000),
|
||||
('2014-07-01 09:00:00.000000005',
|
||||
Timestamp('2014-07-01 09:00:00.000000005'),
|
||||
base_expected + 5)]
|
||||
|
||||
timezones = [(None, 0), ('UTC', 0), (pytz.utc, 0), ('Asia/Tokyo', 9),
|
||||
('US/Eastern', -4), ('dateutil/US/Pacific', -7),
|
||||
(pytz.FixedOffset(-180), -3),
|
||||
(dateutil.tz.tzoffset(None, 18000), 5)]
|
||||
|
||||
for date_str, date, expected in tests:
|
||||
for result in [Timestamp(date_str), Timestamp(date)]:
|
||||
# only with timestring
|
||||
assert result.value == expected
|
||||
assert conversion.pydt_to_i8(result) == expected
|
||||
|
||||
# re-creation shouldn't affect to internal value
|
||||
result = Timestamp(result)
|
||||
assert result.value == expected
|
||||
assert conversion.pydt_to_i8(result) == expected
|
||||
|
||||
# with timezone
|
||||
for tz, offset in timezones:
|
||||
for result in [Timestamp(date_str, tz=tz), Timestamp(date,
|
||||
tz=tz)]:
|
||||
expected_tz = expected - offset * 3600 * 1000000000
|
||||
assert result.value == expected_tz
|
||||
assert conversion.pydt_to_i8(result) == expected_tz
|
||||
|
||||
# should preserve tz
|
||||
result = Timestamp(result)
|
||||
assert result.value == expected_tz
|
||||
assert conversion.pydt_to_i8(result) == expected_tz
|
||||
|
||||
# should convert to UTC
|
||||
if tz is not None:
|
||||
result = Timestamp(result).tz_convert('UTC')
|
||||
else:
|
||||
result = Timestamp(result, tz='UTC')
|
||||
expected_utc = expected - offset * 3600 * 1000000000
|
||||
assert result.value == expected_utc
|
||||
assert conversion.pydt_to_i8(result) == expected_utc
|
||||
|
||||
def test_constructor_with_stringoffset(self):
|
||||
# GH 7833
|
||||
base_str = '2014-07-01 11:00:00+02:00'
|
||||
base_dt = datetime(2014, 7, 1, 9)
|
||||
base_expected = 1404205200000000000
|
||||
|
||||
# confirm base representation is correct
|
||||
import calendar
|
||||
assert (calendar.timegm(base_dt.timetuple()) * 1000000000 ==
|
||||
base_expected)
|
||||
|
||||
tests = [(base_str, base_expected),
|
||||
('2014-07-01 12:00:00+02:00',
|
||||
base_expected + 3600 * 1000000000),
|
||||
('2014-07-01 11:00:00.000008000+02:00', base_expected + 8000),
|
||||
('2014-07-01 11:00:00.000000005+02:00', base_expected + 5)]
|
||||
|
||||
timezones = [(None, 0), ('UTC', 0), (pytz.utc, 0), ('Asia/Tokyo', 9),
|
||||
('US/Eastern', -4), ('dateutil/US/Pacific', -7),
|
||||
(pytz.FixedOffset(-180), -3),
|
||||
(dateutil.tz.tzoffset(None, 18000), 5)]
|
||||
|
||||
for date_str, expected in tests:
|
||||
for result in [Timestamp(date_str)]:
|
||||
# only with timestring
|
||||
assert result.value == expected
|
||||
assert conversion.pydt_to_i8(result) == expected
|
||||
|
||||
# re-creation shouldn't affect to internal value
|
||||
result = Timestamp(result)
|
||||
assert result.value == expected
|
||||
assert conversion.pydt_to_i8(result) == expected
|
||||
|
||||
# with timezone
|
||||
for tz, offset in timezones:
|
||||
result = Timestamp(date_str, tz=tz)
|
||||
expected_tz = expected
|
||||
assert result.value == expected_tz
|
||||
assert conversion.pydt_to_i8(result) == expected_tz
|
||||
|
||||
# should preserve tz
|
||||
result = Timestamp(result)
|
||||
assert result.value == expected_tz
|
||||
assert conversion.pydt_to_i8(result) == expected_tz
|
||||
|
||||
# should convert to UTC
|
||||
result = Timestamp(result).tz_convert('UTC')
|
||||
expected_utc = expected
|
||||
assert result.value == expected_utc
|
||||
assert conversion.pydt_to_i8(result) == expected_utc
|
||||
|
||||
# This should be 2013-11-01 05:00 in UTC
|
||||
# converted to Chicago tz
|
||||
result = Timestamp('2013-11-01 00:00:00-0500', tz='America/Chicago')
|
||||
assert result.value == Timestamp('2013-11-01 05:00').value
|
||||
expected = "Timestamp('2013-11-01 00:00:00-0500', tz='America/Chicago')" # noqa
|
||||
assert repr(result) == expected
|
||||
assert result == eval(repr(result))
|
||||
|
||||
# This should be 2013-11-01 05:00 in UTC
|
||||
# converted to Tokyo tz (+09:00)
|
||||
result = Timestamp('2013-11-01 00:00:00-0500', tz='Asia/Tokyo')
|
||||
assert result.value == Timestamp('2013-11-01 05:00').value
|
||||
expected = "Timestamp('2013-11-01 14:00:00+0900', tz='Asia/Tokyo')"
|
||||
assert repr(result) == expected
|
||||
assert result == eval(repr(result))
|
||||
|
||||
# GH11708
|
||||
# This should be 2015-11-18 10:00 in UTC
|
||||
# converted to Asia/Katmandu
|
||||
result = Timestamp("2015-11-18 15:45:00+05:45", tz="Asia/Katmandu")
|
||||
assert result.value == Timestamp("2015-11-18 10:00").value
|
||||
expected = "Timestamp('2015-11-18 15:45:00+0545', tz='Asia/Katmandu')"
|
||||
assert repr(result) == expected
|
||||
assert result == eval(repr(result))
|
||||
|
||||
# This should be 2015-11-18 10:00 in UTC
|
||||
# converted to Asia/Kolkata
|
||||
result = Timestamp("2015-11-18 15:30:00+05:30", tz="Asia/Kolkata")
|
||||
assert result.value == Timestamp("2015-11-18 10:00").value
|
||||
expected = "Timestamp('2015-11-18 15:30:00+0530', tz='Asia/Kolkata')"
|
||||
assert repr(result) == expected
|
||||
assert result == eval(repr(result))
|
||||
|
||||
def test_constructor_invalid(self):
|
||||
with pytest.raises(TypeError, match='Cannot convert input'):
|
||||
Timestamp(slice(2))
|
||||
with pytest.raises(ValueError, match='Cannot convert Period'):
|
||||
Timestamp(Period('1000-01-01'))
|
||||
|
||||
def test_constructor_invalid_tz(self):
|
||||
# GH#17690
|
||||
with pytest.raises(TypeError, match='must be a datetime.tzinfo'):
|
||||
Timestamp('2017-10-22', tzinfo='US/Eastern')
|
||||
|
||||
with pytest.raises(ValueError, match='at most one of'):
|
||||
Timestamp('2017-10-22', tzinfo=utc, tz='UTC')
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid frequency:"):
|
||||
# GH#5168
|
||||
# case where user tries to pass tz as an arg, not kwarg, gets
|
||||
# interpreted as a `freq`
|
||||
Timestamp('2012-01-01', 'US/Pacific')
|
||||
|
||||
def test_constructor_tz_or_tzinfo(self):
|
||||
# GH#17943, GH#17690, GH#5168
|
||||
stamps = [Timestamp(year=2017, month=10, day=22, tz='UTC'),
|
||||
Timestamp(year=2017, month=10, day=22, tzinfo=utc),
|
||||
Timestamp(year=2017, month=10, day=22, tz=utc),
|
||||
Timestamp(datetime(2017, 10, 22), tzinfo=utc),
|
||||
Timestamp(datetime(2017, 10, 22), tz='UTC'),
|
||||
Timestamp(datetime(2017, 10, 22), tz=utc)]
|
||||
assert all(ts == stamps[0] for ts in stamps)
|
||||
|
||||
def test_constructor_positional(self):
|
||||
# see gh-10758
|
||||
with pytest.raises(TypeError):
|
||||
Timestamp(2000, 1)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(2000, 0, 1)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(2000, 13, 1)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(2000, 1, 0)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(2000, 1, 32)
|
||||
|
||||
# see gh-11630
|
||||
assert (repr(Timestamp(2015, 11, 12)) ==
|
||||
repr(Timestamp('20151112')))
|
||||
assert (repr(Timestamp(2015, 11, 12, 1, 2, 3, 999999)) ==
|
||||
repr(Timestamp('2015-11-12 01:02:03.999999')))
|
||||
|
||||
def test_constructor_keyword(self):
|
||||
# GH 10758
|
||||
with pytest.raises(TypeError):
|
||||
Timestamp(year=2000, month=1)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(year=2000, month=0, day=1)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(year=2000, month=13, day=1)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(year=2000, month=1, day=0)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(year=2000, month=1, day=32)
|
||||
|
||||
assert (repr(Timestamp(year=2015, month=11, day=12)) ==
|
||||
repr(Timestamp('20151112')))
|
||||
|
||||
assert (repr(Timestamp(year=2015, month=11, day=12, hour=1, minute=2,
|
||||
second=3, microsecond=999999)) ==
|
||||
repr(Timestamp('2015-11-12 01:02:03.999999')))
|
||||
|
||||
def test_constructor_fromordinal(self):
|
||||
base = datetime(2000, 1, 1)
|
||||
|
||||
ts = Timestamp.fromordinal(base.toordinal(), freq='D')
|
||||
assert base == ts
|
||||
assert ts.freq == 'D'
|
||||
assert base.toordinal() == ts.toordinal()
|
||||
|
||||
ts = Timestamp.fromordinal(base.toordinal(), tz='US/Eastern')
|
||||
assert Timestamp('2000-01-01', tz='US/Eastern') == ts
|
||||
assert base.toordinal() == ts.toordinal()
|
||||
|
||||
# GH#3042
|
||||
dt = datetime(2011, 4, 16, 0, 0)
|
||||
ts = Timestamp.fromordinal(dt.toordinal())
|
||||
assert ts.to_pydatetime() == dt
|
||||
|
||||
# with a tzinfo
|
||||
stamp = Timestamp('2011-4-16', tz='US/Eastern')
|
||||
dt_tz = stamp.to_pydatetime()
|
||||
ts = Timestamp.fromordinal(dt_tz.toordinal(), tz='US/Eastern')
|
||||
assert ts.to_pydatetime() == dt_tz
|
||||
|
||||
@pytest.mark.parametrize('result', [
|
||||
Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), nanosecond=1),
|
||||
Timestamp(year=2000, month=1, day=2, hour=3, minute=4, second=5,
|
||||
microsecond=6, nanosecond=1),
|
||||
Timestamp(year=2000, month=1, day=2, hour=3, minute=4, second=5,
|
||||
microsecond=6, nanosecond=1, tz='UTC'),
|
||||
Timestamp(2000, 1, 2, 3, 4, 5, 6, 1, None),
|
||||
Timestamp(2000, 1, 2, 3, 4, 5, 6, 1, pytz.UTC)])
|
||||
def test_constructor_nanosecond(self, result):
|
||||
# GH 18898
|
||||
expected = Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), tz=result.tz)
|
||||
expected = expected + Timedelta(nanoseconds=1)
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('z', ['Z0', 'Z00'])
|
||||
def test_constructor_invalid_Z0_isostring(self, z):
|
||||
# GH 8910
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp('2014-11-02 01:00{}'.format(z))
|
||||
|
||||
@pytest.mark.parametrize('arg', ['year', 'month', 'day', 'hour', 'minute',
|
||||
'second', 'microsecond', 'nanosecond'])
|
||||
def test_invalid_date_kwarg_with_string_input(self, arg):
|
||||
kwarg = {arg: 1}
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp('2010-10-10 12:59:59.999999999', **kwarg)
|
||||
|
||||
def test_out_of_bounds_value(self):
|
||||
one_us = np.timedelta64(1).astype('timedelta64[us]')
|
||||
|
||||
# By definition we can't go out of bounds in [ns], so we
|
||||
# convert the datetime64s to [us] so we can go out of bounds
|
||||
min_ts_us = np.datetime64(Timestamp.min).astype('M8[us]')
|
||||
max_ts_us = np.datetime64(Timestamp.max).astype('M8[us]')
|
||||
|
||||
# No error for the min/max datetimes
|
||||
Timestamp(min_ts_us)
|
||||
Timestamp(max_ts_us)
|
||||
|
||||
# One us less than the minimum is an error
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(min_ts_us - one_us)
|
||||
|
||||
# One us more than the maximum is an error
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(max_ts_us + one_us)
|
||||
|
||||
def test_out_of_bounds_string(self):
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp('1676-01-01')
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp('2263-01-01')
|
||||
|
||||
def test_barely_out_of_bounds(self):
|
||||
# GH#19529
|
||||
# GH#19382 close enough to bounds that dropping nanos would result
|
||||
# in an in-bounds datetime
|
||||
with pytest.raises(OutOfBoundsDatetime):
|
||||
Timestamp('2262-04-11 23:47:16.854775808')
|
||||
|
||||
def test_bounds_with_different_units(self):
|
||||
out_of_bounds_dates = ('1677-09-21', '2262-04-12')
|
||||
|
||||
time_units = ('D', 'h', 'm', 's', 'ms', 'us')
|
||||
|
||||
for date_string in out_of_bounds_dates:
|
||||
for unit in time_units:
|
||||
dt64 = np.datetime64(date_string, dtype='M8[%s]' % unit)
|
||||
with pytest.raises(ValueError):
|
||||
Timestamp(dt64)
|
||||
|
||||
in_bounds_dates = ('1677-09-23', '2262-04-11')
|
||||
|
||||
for date_string in in_bounds_dates:
|
||||
for unit in time_units:
|
||||
dt64 = np.datetime64(date_string, dtype='M8[%s]' % unit)
|
||||
Timestamp(dt64)
|
||||
|
||||
def test_min_valid(self):
|
||||
# Ensure that Timestamp.min is a valid Timestamp
|
||||
Timestamp(Timestamp.min)
|
||||
|
||||
def test_max_valid(self):
|
||||
# Ensure that Timestamp.max is a valid Timestamp
|
||||
Timestamp(Timestamp.max)
|
||||
|
||||
def test_now(self):
|
||||
# GH#9000
|
||||
ts_from_string = Timestamp('now')
|
||||
ts_from_method = Timestamp.now()
|
||||
ts_datetime = datetime.now()
|
||||
|
||||
ts_from_string_tz = Timestamp('now', tz='US/Eastern')
|
||||
ts_from_method_tz = Timestamp.now(tz='US/Eastern')
|
||||
|
||||
# Check that the delta between the times is less than 1s (arbitrarily
|
||||
# small)
|
||||
delta = Timedelta(seconds=1)
|
||||
assert abs(ts_from_method - ts_from_string) < delta
|
||||
assert abs(ts_datetime - ts_from_method) < delta
|
||||
assert abs(ts_from_method_tz - ts_from_string_tz) < delta
|
||||
assert (abs(ts_from_string_tz.tz_localize(None) -
|
||||
ts_from_method_tz.tz_localize(None)) < delta)
|
||||
|
||||
def test_today(self):
|
||||
ts_from_string = Timestamp('today')
|
||||
ts_from_method = Timestamp.today()
|
||||
ts_datetime = datetime.today()
|
||||
|
||||
ts_from_string_tz = Timestamp('today', tz='US/Eastern')
|
||||
ts_from_method_tz = Timestamp.today(tz='US/Eastern')
|
||||
|
||||
# Check that the delta between the times is less than 1s (arbitrarily
|
||||
# small)
|
||||
delta = Timedelta(seconds=1)
|
||||
assert abs(ts_from_method - ts_from_string) < delta
|
||||
assert abs(ts_datetime - ts_from_method) < delta
|
||||
assert abs(ts_from_method_tz - ts_from_string_tz) < delta
|
||||
assert (abs(ts_from_string_tz.tz_localize(None) -
|
||||
ts_from_method_tz.tz_localize(None)) < delta)
|
||||
|
||||
@pytest.mark.parametrize('tz', [None, pytz.timezone('US/Pacific')])
|
||||
def test_disallow_setting_tz(self, tz):
|
||||
# GH 3746
|
||||
ts = Timestamp('2010')
|
||||
with pytest.raises(AttributeError):
|
||||
ts.tz = tz
|
||||
|
||||
@pytest.mark.parametrize('offset', ['+0300', '+0200'])
|
||||
def test_construct_timestamp_near_dst(self, offset):
|
||||
# GH 20854
|
||||
expected = Timestamp('2016-10-30 03:00:00{}'.format(offset),
|
||||
tz='Europe/Helsinki')
|
||||
result = Timestamp(expected).tz_convert('Europe/Helsinki')
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('arg', [
|
||||
'2013/01/01 00:00:00+09:00', '2013-01-01 00:00:00+09:00'])
|
||||
def test_construct_with_different_string_format(self, arg):
|
||||
# GH 12064
|
||||
result = Timestamp(arg)
|
||||
expected = Timestamp(datetime(2013, 1, 1), tz=pytz.FixedOffset(540))
|
||||
assert result == expected
|
||||
|
||||
def test_construct_timestamp_preserve_original_frequency(self):
|
||||
# GH 22311
|
||||
result = Timestamp(Timestamp('2010-08-08', freq='D')).freq
|
||||
expected = offsets.Day()
|
||||
assert result == expected
|
||||
|
||||
def test_constructor_invalid_frequency(self):
|
||||
# GH 22311
|
||||
with pytest.raises(ValueError, match="Invalid frequency:"):
|
||||
Timestamp('2012-01-01', freq=[])
|
||||
|
||||
@pytest.mark.parametrize('box', [datetime, Timestamp])
|
||||
def test_depreciate_tz_and_tzinfo_in_datetime_input(self, box):
|
||||
# GH 23579
|
||||
kwargs = {'year': 2018, 'month': 1, 'day': 1, 'tzinfo': utc}
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
Timestamp(box(**kwargs), tz='US/Pacific')
|
||||
|
||||
def test_dont_convert_dateutil_utc_to_pytz_utc(self):
|
||||
result = Timestamp(datetime(2018, 1, 1), tz=tzutc())
|
||||
expected = Timestamp(datetime(2018, 1, 1)).tz_localize(tzutc())
|
||||
assert result == expected
|
||||
|
||||
|
||||
class TestTimestamp(object):
|
||||
|
||||
def test_tz(self):
|
||||
tstr = '2014-02-01 09:00'
|
||||
ts = Timestamp(tstr)
|
||||
local = ts.tz_localize('Asia/Tokyo')
|
||||
assert local.hour == 9
|
||||
assert local == Timestamp(tstr, tz='Asia/Tokyo')
|
||||
conv = local.tz_convert('US/Eastern')
|
||||
assert conv == Timestamp('2014-01-31 19:00', tz='US/Eastern')
|
||||
assert conv.hour == 19
|
||||
|
||||
# preserves nanosecond
|
||||
ts = Timestamp(tstr) + offsets.Nano(5)
|
||||
local = ts.tz_localize('Asia/Tokyo')
|
||||
assert local.hour == 9
|
||||
assert local.nanosecond == 5
|
||||
conv = local.tz_convert('US/Eastern')
|
||||
assert conv.nanosecond == 5
|
||||
assert conv.hour == 19
|
||||
|
||||
def test_utc_z_designator(self):
|
||||
assert get_timezone(Timestamp('2014-11-02 01:00Z').tzinfo) is utc
|
||||
|
||||
def test_asm8(self):
|
||||
np.random.seed(7960929)
|
||||
ns = [Timestamp.min.value, Timestamp.max.value, 1000]
|
||||
|
||||
for n in ns:
|
||||
assert (Timestamp(n).asm8.view('i8') ==
|
||||
np.datetime64(n, 'ns').view('i8') == n)
|
||||
|
||||
assert (Timestamp('nat').asm8.view('i8') ==
|
||||
np.datetime64('nat', 'ns').view('i8'))
|
||||
|
||||
def test_class_ops_pytz(self):
|
||||
def compare(x, y):
|
||||
assert (int(Timestamp(x).value / 1e9) ==
|
||||
int(Timestamp(y).value / 1e9))
|
||||
|
||||
compare(Timestamp.now(), datetime.now())
|
||||
compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
|
||||
compare(Timestamp.utcnow(), datetime.utcnow())
|
||||
compare(Timestamp.today(), datetime.today())
|
||||
current_time = calendar.timegm(datetime.now().utctimetuple())
|
||||
compare(Timestamp.utcfromtimestamp(current_time),
|
||||
datetime.utcfromtimestamp(current_time))
|
||||
compare(Timestamp.fromtimestamp(current_time),
|
||||
datetime.fromtimestamp(current_time))
|
||||
|
||||
date_component = datetime.utcnow()
|
||||
time_component = (date_component + timedelta(minutes=10)).time()
|
||||
compare(Timestamp.combine(date_component, time_component),
|
||||
datetime.combine(date_component, time_component))
|
||||
|
||||
def test_class_ops_dateutil(self):
|
||||
def compare(x, y):
|
||||
assert (int(np.round(Timestamp(x).value / 1e9)) ==
|
||||
int(np.round(Timestamp(y).value / 1e9)))
|
||||
|
||||
compare(Timestamp.now(), datetime.now())
|
||||
compare(Timestamp.now('UTC'), datetime.now(tzutc()))
|
||||
compare(Timestamp.utcnow(), datetime.utcnow())
|
||||
compare(Timestamp.today(), datetime.today())
|
||||
current_time = calendar.timegm(datetime.now().utctimetuple())
|
||||
compare(Timestamp.utcfromtimestamp(current_time),
|
||||
datetime.utcfromtimestamp(current_time))
|
||||
compare(Timestamp.fromtimestamp(current_time),
|
||||
datetime.fromtimestamp(current_time))
|
||||
|
||||
date_component = datetime.utcnow()
|
||||
time_component = (date_component + timedelta(minutes=10)).time()
|
||||
compare(Timestamp.combine(date_component, time_component),
|
||||
datetime.combine(date_component, time_component))
|
||||
|
||||
def test_basics_nanos(self):
|
||||
val = np.int64(946684800000000000).view('M8[ns]')
|
||||
stamp = Timestamp(val.view('i8') + 500)
|
||||
assert stamp.year == 2000
|
||||
assert stamp.month == 1
|
||||
assert stamp.microsecond == 0
|
||||
assert stamp.nanosecond == 500
|
||||
|
||||
# GH 14415
|
||||
val = np.iinfo(np.int64).min + 80000000000000
|
||||
stamp = Timestamp(val)
|
||||
assert stamp.year == 1677
|
||||
assert stamp.month == 9
|
||||
assert stamp.day == 21
|
||||
assert stamp.microsecond == 145224
|
||||
assert stamp.nanosecond == 192
|
||||
|
||||
@pytest.mark.parametrize('value, check_kwargs', [
|
||||
[946688461000000000, {}],
|
||||
[946688461000000000 / long(1000), dict(unit='us')],
|
||||
[946688461000000000 / long(1000000), dict(unit='ms')],
|
||||
[946688461000000000 / long(1000000000), dict(unit='s')],
|
||||
[10957, dict(unit='D', h=0)],
|
||||
pytest.param((946688461000000000 + 500000) / long(1000000000),
|
||||
dict(unit='s', us=499, ns=964),
|
||||
marks=pytest.mark.skipif(not PY3,
|
||||
reason='using truediv, so these'
|
||||
' are like floats')),
|
||||
pytest.param((946688461000000000 + 500000000) / long(1000000000),
|
||||
dict(unit='s', us=500000),
|
||||
marks=pytest.mark.skipif(not PY3,
|
||||
reason='using truediv, so these'
|
||||
' are like floats')),
|
||||
pytest.param((946688461000000000 + 500000) / long(1000000),
|
||||
dict(unit='ms', us=500),
|
||||
marks=pytest.mark.skipif(not PY3,
|
||||
reason='using truediv, so these'
|
||||
' are like floats')),
|
||||
pytest.param((946688461000000000 + 500000) / long(1000000000),
|
||||
dict(unit='s'),
|
||||
marks=pytest.mark.skipif(PY3,
|
||||
reason='get chopped in py2')),
|
||||
pytest.param((946688461000000000 + 500000000) / long(1000000000),
|
||||
dict(unit='s'),
|
||||
marks=pytest.mark.skipif(PY3,
|
||||
reason='get chopped in py2')),
|
||||
pytest.param((946688461000000000 + 500000) / long(1000000),
|
||||
dict(unit='ms'),
|
||||
marks=pytest.mark.skipif(PY3,
|
||||
reason='get chopped in py2')),
|
||||
[(946688461000000000 + 500000) / long(1000), dict(unit='us', us=500)],
|
||||
[(946688461000000000 + 500000000) / long(1000000),
|
||||
dict(unit='ms', us=500000)],
|
||||
[946688461000000000 / 1000.0 + 5, dict(unit='us', us=5)],
|
||||
[946688461000000000 / 1000.0 + 5000, dict(unit='us', us=5000)],
|
||||
[946688461000000000 / 1000000.0 + 0.5, dict(unit='ms', us=500)],
|
||||
[946688461000000000 / 1000000.0 + 0.005, dict(unit='ms', us=5, ns=5)],
|
||||
[946688461000000000 / 1000000000.0 + 0.5, dict(unit='s', us=500000)],
|
||||
[10957 + 0.5, dict(unit='D', h=12)]])
|
||||
def test_unit(self, value, check_kwargs):
|
||||
def check(value, unit=None, h=1, s=1, us=0, ns=0):
|
||||
stamp = Timestamp(value, unit=unit)
|
||||
assert stamp.year == 2000
|
||||
assert stamp.month == 1
|
||||
assert stamp.day == 1
|
||||
assert stamp.hour == h
|
||||
if unit != 'D':
|
||||
assert stamp.minute == 1
|
||||
assert stamp.second == s
|
||||
assert stamp.microsecond == us
|
||||
else:
|
||||
assert stamp.minute == 0
|
||||
assert stamp.second == 0
|
||||
assert stamp.microsecond == 0
|
||||
assert stamp.nanosecond == ns
|
||||
|
||||
check(value, **check_kwargs)
|
||||
|
||||
def test_roundtrip(self):
|
||||
|
||||
# test value to string and back conversions
|
||||
# further test accessors
|
||||
base = Timestamp('20140101 00:00:00')
|
||||
|
||||
result = Timestamp(base.value + Timedelta('5ms').value)
|
||||
assert result == Timestamp(str(base) + ".005000")
|
||||
assert result.microsecond == 5000
|
||||
|
||||
result = Timestamp(base.value + Timedelta('5us').value)
|
||||
assert result == Timestamp(str(base) + ".000005")
|
||||
assert result.microsecond == 5
|
||||
|
||||
result = Timestamp(base.value + Timedelta('5ns').value)
|
||||
assert result == Timestamp(str(base) + ".000000005")
|
||||
assert result.nanosecond == 5
|
||||
assert result.microsecond == 0
|
||||
|
||||
result = Timestamp(base.value + Timedelta('6ms 5us').value)
|
||||
assert result == Timestamp(str(base) + ".006005")
|
||||
assert result.microsecond == 5 + 6 * 1000
|
||||
|
||||
result = Timestamp(base.value + Timedelta('200ms 5us').value)
|
||||
assert result == Timestamp(str(base) + ".200005")
|
||||
assert result.microsecond == 5 + 200 * 1000
|
||||
|
||||
def test_hash_equivalent(self):
|
||||
d = {datetime(2011, 1, 1): 5}
|
||||
stamp = Timestamp(datetime(2011, 1, 1))
|
||||
assert d[stamp] == 5
|
||||
|
||||
|
||||
class TestTimestampNsOperations(object):
|
||||
|
||||
def setup_method(self, method):
|
||||
self.timestamp = Timestamp(datetime.utcnow())
|
||||
|
||||
def assert_ns_timedelta(self, modified_timestamp, expected_value):
|
||||
value = self.timestamp.value
|
||||
modified_value = modified_timestamp.value
|
||||
|
||||
assert modified_value - value == expected_value
|
||||
|
||||
def test_timedelta_ns_arithmetic(self):
|
||||
self.assert_ns_timedelta(self.timestamp + np.timedelta64(-123, 'ns'),
|
||||
-123)
|
||||
|
||||
def test_timedelta_ns_based_arithmetic(self):
|
||||
self.assert_ns_timedelta(self.timestamp + np.timedelta64(
|
||||
1234567898, 'ns'), 1234567898)
|
||||
|
||||
def test_timedelta_us_arithmetic(self):
|
||||
self.assert_ns_timedelta(self.timestamp + np.timedelta64(-123, 'us'),
|
||||
-123000)
|
||||
|
||||
def test_timedelta_ms_arithmetic(self):
|
||||
time = self.timestamp + np.timedelta64(-123, 'ms')
|
||||
self.assert_ns_timedelta(time, -123000000)
|
||||
|
||||
def test_nanosecond_string_parsing(self):
|
||||
ts = Timestamp('2013-05-01 07:15:45.123456789')
|
||||
# GH 7878
|
||||
expected_repr = '2013-05-01 07:15:45.123456789'
|
||||
expected_value = 1367392545123456789
|
||||
assert ts.value == expected_value
|
||||
assert expected_repr in repr(ts)
|
||||
|
||||
ts = Timestamp('2013-05-01 07:15:45.123456789+09:00', tz='Asia/Tokyo')
|
||||
assert ts.value == expected_value - 9 * 3600 * 1000000000
|
||||
assert expected_repr in repr(ts)
|
||||
|
||||
ts = Timestamp('2013-05-01 07:15:45.123456789', tz='UTC')
|
||||
assert ts.value == expected_value
|
||||
assert expected_repr in repr(ts)
|
||||
|
||||
ts = Timestamp('2013-05-01 07:15:45.123456789', tz='US/Eastern')
|
||||
assert ts.value == expected_value + 4 * 3600 * 1000000000
|
||||
assert expected_repr in repr(ts)
|
||||
|
||||
# GH 10041
|
||||
ts = Timestamp('20130501T071545.123456789')
|
||||
assert ts.value == expected_value
|
||||
assert expected_repr in repr(ts)
|
||||
|
||||
def test_nanosecond_timestamp(self):
|
||||
# GH 7610
|
||||
expected = 1293840000000000005
|
||||
t = Timestamp('2011-01-01') + offsets.Nano(5)
|
||||
assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
|
||||
assert t.value == expected
|
||||
assert t.nanosecond == 5
|
||||
|
||||
t = Timestamp(t)
|
||||
assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
|
||||
assert t.value == expected
|
||||
assert t.nanosecond == 5
|
||||
|
||||
t = Timestamp(np_datetime64_compat('2011-01-01 00:00:00.000000005Z'))
|
||||
assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
|
||||
assert t.value == expected
|
||||
assert t.nanosecond == 5
|
||||
|
||||
expected = 1293840000000000010
|
||||
t = t + offsets.Nano(5)
|
||||
assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
|
||||
assert t.value == expected
|
||||
assert t.nanosecond == 10
|
||||
|
||||
t = Timestamp(t)
|
||||
assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
|
||||
assert t.value == expected
|
||||
assert t.nanosecond == 10
|
||||
|
||||
t = Timestamp(np_datetime64_compat('2011-01-01 00:00:00.000000010Z'))
|
||||
assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
|
||||
assert t.value == expected
|
||||
assert t.nanosecond == 10
|
||||
|
||||
|
||||
class TestTimestampToJulianDate(object):
|
||||
|
||||
def test_compare_1700(self):
|
||||
r = Timestamp('1700-06-23').to_julian_date()
|
||||
assert r == 2342145.5
|
||||
|
||||
def test_compare_2000(self):
|
||||
r = Timestamp('2000-04-12').to_julian_date()
|
||||
assert r == 2451646.5
|
||||
|
||||
def test_compare_2100(self):
|
||||
r = Timestamp('2100-08-12').to_julian_date()
|
||||
assert r == 2488292.5
|
||||
|
||||
def test_compare_hour01(self):
|
||||
r = Timestamp('2000-08-12T01:00:00').to_julian_date()
|
||||
assert r == 2451768.5416666666666666
|
||||
|
||||
def test_compare_hour13(self):
|
||||
r = Timestamp('2000-08-12T13:00:00').to_julian_date()
|
||||
assert r == 2451769.0416666666666666
|
||||
|
||||
|
||||
class TestTimestampConversion(object):
|
||||
def test_conversion(self):
|
||||
# GH#9255
|
||||
ts = Timestamp('2000-01-01')
|
||||
|
||||
result = ts.to_pydatetime()
|
||||
expected = datetime(2000, 1, 1)
|
||||
assert result == expected
|
||||
assert type(result) == type(expected)
|
||||
|
||||
result = ts.to_datetime64()
|
||||
expected = np.datetime64(ts.value, 'ns')
|
||||
assert result == expected
|
||||
assert type(result) == type(expected)
|
||||
assert result.dtype == expected.dtype
|
||||
|
||||
def test_to_pydatetime_nonzero_nano(self):
|
||||
ts = Timestamp('2011-01-01 9:00:00.123456789')
|
||||
|
||||
# Warn the user of data loss (nanoseconds).
|
||||
with tm.assert_produces_warning(UserWarning,
|
||||
check_stacklevel=False):
|
||||
expected = datetime(2011, 1, 1, 9, 0, 0, 123456)
|
||||
result = ts.to_pydatetime()
|
||||
assert result == expected
|
||||
|
||||
def test_timestamp_to_datetime(self):
|
||||
stamp = Timestamp('20090415', tz='US/Eastern', freq='D')
|
||||
dtval = stamp.to_pydatetime()
|
||||
assert stamp == dtval
|
||||
assert stamp.tzinfo == dtval.tzinfo
|
||||
|
||||
def test_timestamp_to_datetime_dateutil(self):
|
||||
stamp = Timestamp('20090415', tz='dateutil/US/Eastern', freq='D')
|
||||
dtval = stamp.to_pydatetime()
|
||||
assert stamp == dtval
|
||||
assert stamp.tzinfo == dtval.tzinfo
|
||||
|
||||
def test_timestamp_to_datetime_explicit_pytz(self):
|
||||
stamp = Timestamp('20090415', tz=pytz.timezone('US/Eastern'), freq='D')
|
||||
dtval = stamp.to_pydatetime()
|
||||
assert stamp == dtval
|
||||
assert stamp.tzinfo == dtval.tzinfo
|
||||
|
||||
@td.skip_if_windows_python_3
|
||||
def test_timestamp_to_datetime_explicit_dateutil(self):
|
||||
stamp = Timestamp('20090415', tz=gettz('US/Eastern'), freq='D')
|
||||
dtval = stamp.to_pydatetime()
|
||||
assert stamp == dtval
|
||||
assert stamp.tzinfo == dtval.tzinfo
|
||||
|
||||
def test_to_datetime_bijective(self):
|
||||
# Ensure that converting to datetime and back only loses precision
|
||||
# by going from nanoseconds to microseconds.
|
||||
exp_warning = None if Timestamp.max.nanosecond == 0 else UserWarning
|
||||
with tm.assert_produces_warning(exp_warning, check_stacklevel=False):
|
||||
assert (Timestamp(Timestamp.max.to_pydatetime()).value / 1000 ==
|
||||
Timestamp.max.value / 1000)
|
||||
|
||||
exp_warning = None if Timestamp.min.nanosecond == 0 else UserWarning
|
||||
with tm.assert_produces_warning(exp_warning, check_stacklevel=False):
|
||||
assert (Timestamp(Timestamp.min.to_pydatetime()).value / 1000 ==
|
||||
Timestamp.min.value / 1000)
|
||||
|
||||
def test_to_period_tz_warning(self):
|
||||
# GH#21333 make sure a warning is issued when timezone
|
||||
# info is lost
|
||||
ts = Timestamp('2009-04-15 16:17:18', tz='US/Eastern')
|
||||
with tm.assert_produces_warning(UserWarning):
|
||||
# warning that timezone info will be lost
|
||||
ts.to_period('D')
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Tests for Timestamp timezone-related methods
|
||||
"""
|
||||
from datetime import date, datetime, timedelta
|
||||
from distutils.version import LooseVersion
|
||||
|
||||
import dateutil
|
||||
from dateutil.tz import gettz, tzoffset
|
||||
import pytest
|
||||
import pytz
|
||||
from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError
|
||||
|
||||
from pandas._libs.tslibs import timezones
|
||||
from pandas.errors import OutOfBoundsDatetime
|
||||
import pandas.util._test_decorators as td
|
||||
|
||||
from pandas import NaT, Timestamp
|
||||
import pandas.util.testing as tm
|
||||
|
||||
|
||||
class TestTimestampTZOperations(object):
|
||||
# --------------------------------------------------------------
|
||||
# Timestamp.tz_localize
|
||||
|
||||
def test_tz_localize_pushes_out_of_bounds(self):
|
||||
# GH#12677
|
||||
# tz_localize that pushes away from the boundary is OK
|
||||
pac = Timestamp.min.tz_localize('US/Pacific')
|
||||
assert pac.value > Timestamp.min.value
|
||||
pac.tz_convert('Asia/Tokyo') # tz_convert doesn't change value
|
||||
with pytest.raises(OutOfBoundsDatetime):
|
||||
Timestamp.min.tz_localize('Asia/Tokyo')
|
||||
|
||||
# tz_localize that pushes away from the boundary is OK
|
||||
tokyo = Timestamp.max.tz_localize('Asia/Tokyo')
|
||||
assert tokyo.value < Timestamp.max.value
|
||||
tokyo.tz_convert('US/Pacific') # tz_convert doesn't change value
|
||||
with pytest.raises(OutOfBoundsDatetime):
|
||||
Timestamp.max.tz_localize('US/Pacific')
|
||||
|
||||
def test_tz_localize_ambiguous_bool(self):
|
||||
# make sure that we are correctly accepting bool values as ambiguous
|
||||
# GH#14402
|
||||
ts = Timestamp('2015-11-01 01:00:03')
|
||||
expected0 = Timestamp('2015-11-01 01:00:03-0500', tz='US/Central')
|
||||
expected1 = Timestamp('2015-11-01 01:00:03-0600', tz='US/Central')
|
||||
|
||||
with pytest.raises(pytz.AmbiguousTimeError):
|
||||
ts.tz_localize('US/Central')
|
||||
|
||||
result = ts.tz_localize('US/Central', ambiguous=True)
|
||||
assert result == expected0
|
||||
|
||||
result = ts.tz_localize('US/Central', ambiguous=False)
|
||||
assert result == expected1
|
||||
|
||||
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')
|
||||
|
||||
@pytest.mark.parametrize('stamp, tz', [
|
||||
('2015-03-08 02:00', 'US/Eastern'),
|
||||
('2015-03-08 02:30', 'US/Pacific'),
|
||||
('2015-03-29 02:00', 'Europe/Paris'),
|
||||
('2015-03-29 02:30', 'Europe/Belgrade')])
|
||||
@pytest.mark.filterwarnings('ignore::FutureWarning')
|
||||
def test_tz_localize_nonexistent(self, stamp, tz):
|
||||
# GH#13057
|
||||
ts = Timestamp(stamp)
|
||||
with pytest.raises(NonExistentTimeError):
|
||||
ts.tz_localize(tz)
|
||||
# GH 22644
|
||||
with pytest.raises(NonExistentTimeError):
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
ts.tz_localize(tz, errors='raise')
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
assert ts.tz_localize(tz, errors='coerce') is NaT
|
||||
|
||||
def test_tz_localize_errors_ambiguous(self):
|
||||
# GH#13057
|
||||
ts = Timestamp('2015-11-1 01:00')
|
||||
with pytest.raises(AmbiguousTimeError):
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
ts.tz_localize('US/Pacific', errors='coerce')
|
||||
|
||||
@pytest.mark.filterwarnings('ignore::FutureWarning')
|
||||
def test_tz_localize_errors_invalid_arg(self):
|
||||
# GH 22644
|
||||
tz = 'Europe/Warsaw'
|
||||
ts = Timestamp('2015-03-29 02:00:00')
|
||||
with pytest.raises(ValueError):
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
ts.tz_localize(tz, errors='foo')
|
||||
|
||||
def test_tz_localize_errors_coerce(self):
|
||||
# GH 22644
|
||||
# make sure errors='coerce' gets mapped correctly to nonexistent
|
||||
tz = 'Europe/Warsaw'
|
||||
ts = Timestamp('2015-03-29 02:00:00')
|
||||
with tm.assert_produces_warning(FutureWarning):
|
||||
result = ts.tz_localize(tz, errors='coerce')
|
||||
expected = ts.tz_localize(tz, nonexistent='NaT')
|
||||
assert result is expected
|
||||
|
||||
@pytest.mark.parametrize('stamp', ['2014-02-01 09:00', '2014-07-08 09:00',
|
||||
'2014-11-01 17:00', '2014-11-05 00:00'])
|
||||
def test_tz_localize_roundtrip(self, stamp, tz_aware_fixture):
|
||||
tz = tz_aware_fixture
|
||||
ts = Timestamp(stamp)
|
||||
localized = ts.tz_localize(tz)
|
||||
assert localized == Timestamp(stamp, tz=tz)
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
localized.tz_localize(tz)
|
||||
|
||||
reset = localized.tz_localize(None)
|
||||
assert reset == ts
|
||||
assert reset.tzinfo is None
|
||||
|
||||
def test_tz_localize_ambiguous_compat(self):
|
||||
# validate that pytz and dateutil are compat for dst
|
||||
# when the transition happens
|
||||
naive = Timestamp('2013-10-27 01:00:00')
|
||||
|
||||
pytz_zone = 'Europe/London'
|
||||
dateutil_zone = 'dateutil/Europe/London'
|
||||
result_pytz = naive.tz_localize(pytz_zone, ambiguous=0)
|
||||
result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=0)
|
||||
assert result_pytz.value == result_dateutil.value
|
||||
assert result_pytz.value == 1382835600000000000
|
||||
|
||||
if LooseVersion(dateutil.__version__) < LooseVersion('2.6.0'):
|
||||
# dateutil 2.6 buggy w.r.t. ambiguous=0
|
||||
# see gh-14621
|
||||
# see https://github.com/dateutil/dateutil/issues/321
|
||||
assert (result_pytz.to_pydatetime().tzname() ==
|
||||
result_dateutil.to_pydatetime().tzname())
|
||||
assert str(result_pytz) == str(result_dateutil)
|
||||
elif LooseVersion(dateutil.__version__) > LooseVersion('2.6.0'):
|
||||
# fixed ambiguous behavior
|
||||
assert result_pytz.to_pydatetime().tzname() == 'GMT'
|
||||
assert result_dateutil.to_pydatetime().tzname() == 'BST'
|
||||
assert str(result_pytz) != str(result_dateutil)
|
||||
|
||||
# 1 hour difference
|
||||
result_pytz = naive.tz_localize(pytz_zone, ambiguous=1)
|
||||
result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=1)
|
||||
assert result_pytz.value == result_dateutil.value
|
||||
assert result_pytz.value == 1382832000000000000
|
||||
|
||||
# dateutil < 2.6 is buggy w.r.t. ambiguous timezones
|
||||
if LooseVersion(dateutil.__version__) > LooseVersion('2.5.3'):
|
||||
# see gh-14621
|
||||
assert str(result_pytz) == str(result_dateutil)
|
||||
assert (result_pytz.to_pydatetime().tzname() ==
|
||||
result_dateutil.to_pydatetime().tzname())
|
||||
|
||||
@pytest.mark.parametrize('tz', [pytz.timezone('US/Eastern'),
|
||||
gettz('US/Eastern'),
|
||||
'US/Eastern', 'dateutil/US/Eastern'])
|
||||
def test_timestamp_tz_localize(self, tz):
|
||||
stamp = Timestamp('3/11/2012 04:00')
|
||||
|
||||
result = stamp.tz_localize(tz)
|
||||
expected = Timestamp('3/11/2012 04:00', tz=tz)
|
||||
assert result.hour == expected.hour
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('start_ts, tz, end_ts, shift', [
|
||||
['2015-03-29 02:20:00', 'Europe/Warsaw', '2015-03-29 03:00:00',
|
||||
'forward'],
|
||||
['2015-03-29 02:20:00', 'Europe/Warsaw',
|
||||
'2015-03-29 01:59:59.999999999', 'backward'],
|
||||
['2015-03-29 02:20:00', 'Europe/Warsaw',
|
||||
'2015-03-29 03:20:00', timedelta(hours=1)],
|
||||
['2015-03-29 02:20:00', 'Europe/Warsaw',
|
||||
'2015-03-29 01:20:00', timedelta(hours=-1)],
|
||||
['2018-03-11 02:33:00', 'US/Pacific', '2018-03-11 03:00:00',
|
||||
'forward'],
|
||||
['2018-03-11 02:33:00', 'US/Pacific', '2018-03-11 01:59:59.999999999',
|
||||
'backward'],
|
||||
['2018-03-11 02:33:00', 'US/Pacific', '2018-03-11 03:33:00',
|
||||
timedelta(hours=1)],
|
||||
['2018-03-11 02:33:00', 'US/Pacific', '2018-03-11 01:33:00',
|
||||
timedelta(hours=-1)]
|
||||
])
|
||||
@pytest.mark.parametrize('tz_type', ['', 'dateutil/'])
|
||||
def test_timestamp_tz_localize_nonexistent_shift(self, start_ts, tz,
|
||||
end_ts, shift,
|
||||
tz_type):
|
||||
# GH 8917, 24466
|
||||
tz = tz_type + tz
|
||||
if isinstance(shift, str):
|
||||
shift = 'shift_' + shift
|
||||
ts = Timestamp(start_ts)
|
||||
result = ts.tz_localize(tz, nonexistent=shift)
|
||||
expected = Timestamp(end_ts).tz_localize(tz)
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('offset', [-1, 1])
|
||||
@pytest.mark.parametrize('tz_type', ['', 'dateutil/'])
|
||||
def test_timestamp_tz_localize_nonexistent_shift_invalid(self, offset,
|
||||
tz_type):
|
||||
# GH 8917, 24466
|
||||
tz = tz_type + 'Europe/Warsaw'
|
||||
ts = Timestamp('2015-03-29 02:20:00')
|
||||
msg = "The provided timedelta will relocalize on a nonexistent time"
|
||||
with pytest.raises(ValueError, match=msg):
|
||||
ts.tz_localize(tz, nonexistent=timedelta(seconds=offset))
|
||||
|
||||
@pytest.mark.parametrize('tz', ['Europe/Warsaw', 'dateutil/Europe/Warsaw'])
|
||||
def test_timestamp_tz_localize_nonexistent_NaT(self, tz):
|
||||
# GH 8917
|
||||
ts = Timestamp('2015-03-29 02:20:00')
|
||||
result = ts.tz_localize(tz, nonexistent='NaT')
|
||||
assert result is NaT
|
||||
|
||||
@pytest.mark.parametrize('tz', ['Europe/Warsaw', 'dateutil/Europe/Warsaw'])
|
||||
def test_timestamp_tz_localize_nonexistent_raise(self, tz):
|
||||
# GH 8917
|
||||
ts = Timestamp('2015-03-29 02:20:00')
|
||||
with pytest.raises(pytz.NonExistentTimeError):
|
||||
ts.tz_localize(tz, nonexistent='raise')
|
||||
with pytest.raises(ValueError):
|
||||
ts.tz_localize(tz, nonexistent='foo')
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Timestamp.tz_convert
|
||||
|
||||
@pytest.mark.parametrize('stamp', ['2014-02-01 09:00', '2014-07-08 09:00',
|
||||
'2014-11-01 17:00', '2014-11-05 00:00'])
|
||||
def test_tz_convert_roundtrip(self, stamp, tz_aware_fixture):
|
||||
tz = tz_aware_fixture
|
||||
|
||||
ts = Timestamp(stamp, tz='UTC')
|
||||
converted = ts.tz_convert(tz)
|
||||
|
||||
reset = converted.tz_convert(None)
|
||||
assert reset == Timestamp(stamp)
|
||||
assert reset.tzinfo is None
|
||||
assert reset == converted.tz_convert('UTC').tz_localize(None)
|
||||
|
||||
@pytest.mark.parametrize('tzstr', ['US/Eastern', 'dateutil/US/Eastern'])
|
||||
def test_astimezone(self, tzstr):
|
||||
# astimezone is an alias for tz_convert, so keep it with
|
||||
# the tz_convert tests
|
||||
utcdate = Timestamp('3/11/2012 22:00', tz='UTC')
|
||||
expected = utcdate.tz_convert(tzstr)
|
||||
result = utcdate.astimezone(tzstr)
|
||||
assert expected == result
|
||||
assert isinstance(result, Timestamp)
|
||||
|
||||
@td.skip_if_windows
|
||||
def test_tz_convert_utc_with_system_utc(self):
|
||||
from pandas._libs.tslibs.timezones import maybe_get_tz
|
||||
|
||||
# from system utc to real utc
|
||||
ts = Timestamp('2001-01-05 11:56', tz=maybe_get_tz('dateutil/UTC'))
|
||||
# check that the time hasn't changed.
|
||||
assert ts == ts.tz_convert(dateutil.tz.tzutc())
|
||||
|
||||
# from system utc to real utc
|
||||
ts = Timestamp('2001-01-05 11:56', tz=maybe_get_tz('dateutil/UTC'))
|
||||
# check that the time hasn't changed.
|
||||
assert ts == ts.tz_convert(dateutil.tz.tzutc())
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Timestamp.__init__ with tz str or tzinfo
|
||||
|
||||
def test_timestamp_constructor_tz_utc(self):
|
||||
utc_stamp = Timestamp('3/11/2012 05:00', tz='utc')
|
||||
assert utc_stamp.tzinfo is pytz.utc
|
||||
assert utc_stamp.hour == 5
|
||||
|
||||
utc_stamp = Timestamp('3/11/2012 05:00').tz_localize('utc')
|
||||
assert utc_stamp.hour == 5
|
||||
|
||||
def test_timestamp_to_datetime_tzoffset(self):
|
||||
tzinfo = tzoffset(None, 7200)
|
||||
expected = Timestamp('3/11/2012 04:00', tz=tzinfo)
|
||||
result = Timestamp(expected.to_pydatetime())
|
||||
assert expected == result
|
||||
|
||||
def test_timestamp_constructor_near_dst_boundary(self):
|
||||
# GH#11481 & GH#15777
|
||||
# Naive string timestamps were being localized incorrectly
|
||||
# with tz_convert_single instead of tz_localize_to_utc
|
||||
|
||||
for tz in ['Europe/Brussels', 'Europe/Prague']:
|
||||
result = Timestamp('2015-10-25 01:00', tz=tz)
|
||||
expected = Timestamp('2015-10-25 01:00').tz_localize(tz)
|
||||
assert result == expected
|
||||
|
||||
with pytest.raises(pytz.AmbiguousTimeError):
|
||||
Timestamp('2015-10-25 02:00', tz=tz)
|
||||
|
||||
result = Timestamp('2017-03-26 01:00', tz='Europe/Paris')
|
||||
expected = Timestamp('2017-03-26 01:00').tz_localize('Europe/Paris')
|
||||
assert result == expected
|
||||
|
||||
with pytest.raises(pytz.NonExistentTimeError):
|
||||
Timestamp('2017-03-26 02:00', tz='Europe/Paris')
|
||||
|
||||
# GH#11708
|
||||
naive = Timestamp('2015-11-18 10:00:00')
|
||||
result = naive.tz_localize('UTC').tz_convert('Asia/Kolkata')
|
||||
expected = Timestamp('2015-11-18 15:30:00+0530', tz='Asia/Kolkata')
|
||||
assert result == expected
|
||||
|
||||
# GH#15823
|
||||
result = Timestamp('2017-03-26 00:00', tz='Europe/Paris')
|
||||
expected = Timestamp('2017-03-26 00:00:00+0100', tz='Europe/Paris')
|
||||
assert result == expected
|
||||
|
||||
result = Timestamp('2017-03-26 01:00', tz='Europe/Paris')
|
||||
expected = Timestamp('2017-03-26 01:00:00+0100', tz='Europe/Paris')
|
||||
assert result == expected
|
||||
|
||||
with pytest.raises(pytz.NonExistentTimeError):
|
||||
Timestamp('2017-03-26 02:00', tz='Europe/Paris')
|
||||
|
||||
result = Timestamp('2017-03-26 02:00:00+0100', tz='Europe/Paris')
|
||||
naive = Timestamp(result.value)
|
||||
expected = naive.tz_localize('UTC').tz_convert('Europe/Paris')
|
||||
assert result == expected
|
||||
|
||||
result = Timestamp('2017-03-26 03:00', tz='Europe/Paris')
|
||||
expected = Timestamp('2017-03-26 03:00:00+0200', tz='Europe/Paris')
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('tz', [pytz.timezone('US/Eastern'),
|
||||
gettz('US/Eastern'),
|
||||
'US/Eastern', 'dateutil/US/Eastern'])
|
||||
def test_timestamp_constructed_by_date_and_tz(self, tz):
|
||||
# GH#2993, Timestamp cannot be constructed by datetime.date
|
||||
# and tz correctly
|
||||
|
||||
result = Timestamp(date(2012, 3, 11), tz=tz)
|
||||
|
||||
expected = Timestamp('3/11/2012', tz=tz)
|
||||
assert result.hour == expected.hour
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('tz', [pytz.timezone('US/Eastern'),
|
||||
gettz('US/Eastern'),
|
||||
'US/Eastern', 'dateutil/US/Eastern'])
|
||||
def test_timestamp_add_timedelta_push_over_dst_boundary(self, tz):
|
||||
# GH#1389
|
||||
|
||||
# 4 hours before DST transition
|
||||
stamp = Timestamp('3/10/2012 22:00', tz=tz)
|
||||
|
||||
result = stamp + timedelta(hours=6)
|
||||
|
||||
# spring forward, + "7" hours
|
||||
expected = Timestamp('3/11/2012 05:00', tz=tz)
|
||||
|
||||
assert result == expected
|
||||
|
||||
def test_timestamp_timetz_equivalent_with_datetime_tz(self,
|
||||
tz_naive_fixture):
|
||||
# GH21358
|
||||
tz = timezones.maybe_get_tz(tz_naive_fixture)
|
||||
|
||||
stamp = Timestamp('2018-06-04 10:20:30', tz=tz)
|
||||
_datetime = datetime(2018, 6, 4, hour=10,
|
||||
minute=20, second=30, tzinfo=tz)
|
||||
|
||||
result = stamp.timetz()
|
||||
expected = _datetime.timetz()
|
||||
|
||||
assert result == expected
|
||||
+364
@@ -0,0 +1,364 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from datetime import datetime
|
||||
|
||||
from dateutil.tz import gettz
|
||||
import pytest
|
||||
import pytz
|
||||
from pytz import utc
|
||||
|
||||
from pandas._libs.tslibs import conversion
|
||||
from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG
|
||||
from pandas.compat import PY3
|
||||
import pandas.util._test_decorators as td
|
||||
|
||||
from pandas import NaT, Timestamp
|
||||
import pandas.util.testing as tm
|
||||
|
||||
from pandas.tseries.frequencies import to_offset
|
||||
|
||||
|
||||
class TestTimestampUnaryOps(object):
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# Timestamp.round
|
||||
@pytest.mark.parametrize('timestamp, freq, expected', [
|
||||
('20130101 09:10:11', 'D', '20130101'),
|
||||
('20130101 19:10:11', 'D', '20130102'),
|
||||
('20130201 12:00:00', 'D', '20130202'),
|
||||
('20130104 12:00:00', 'D', '20130105'),
|
||||
('2000-01-05 05:09:15.13', 'D', '2000-01-05 00:00:00'),
|
||||
('2000-01-05 05:09:15.13', 'H', '2000-01-05 05:00:00'),
|
||||
('2000-01-05 05:09:15.13', 'S', '2000-01-05 05:09:15')
|
||||
])
|
||||
def test_round_frequencies(self, timestamp, freq, expected):
|
||||
dt = Timestamp(timestamp)
|
||||
result = dt.round(freq)
|
||||
expected = Timestamp(expected)
|
||||
assert result == expected
|
||||
|
||||
def test_round_tzaware(self):
|
||||
dt = Timestamp('20130101 09:10:11', tz='US/Eastern')
|
||||
result = dt.round('D')
|
||||
expected = Timestamp('20130101', tz='US/Eastern')
|
||||
assert result == expected
|
||||
|
||||
dt = Timestamp('20130101 09:10:11', tz='US/Eastern')
|
||||
result = dt.round('s')
|
||||
assert result == dt
|
||||
|
||||
def test_round_30min(self):
|
||||
# round
|
||||
dt = Timestamp('20130104 12:32:00')
|
||||
result = dt.round('30Min')
|
||||
expected = Timestamp('20130104 12:30:00')
|
||||
assert result == expected
|
||||
|
||||
def test_round_subsecond(self):
|
||||
# GH#14440 & GH#15578
|
||||
result = Timestamp('2016-10-17 12:00:00.0015').round('ms')
|
||||
expected = Timestamp('2016-10-17 12:00:00.002000')
|
||||
assert result == expected
|
||||
|
||||
result = Timestamp('2016-10-17 12:00:00.00149').round('ms')
|
||||
expected = Timestamp('2016-10-17 12:00:00.001000')
|
||||
assert result == expected
|
||||
|
||||
ts = Timestamp('2016-10-17 12:00:00.0015')
|
||||
for freq in ['us', 'ns']:
|
||||
assert ts == ts.round(freq)
|
||||
|
||||
result = Timestamp('2016-10-17 12:00:00.001501031').round('10ns')
|
||||
expected = Timestamp('2016-10-17 12:00:00.001501030')
|
||||
assert result == expected
|
||||
|
||||
def test_round_nonstandard_freq(self):
|
||||
with tm.assert_produces_warning(False):
|
||||
Timestamp('2016-10-17 12:00:00.001501031').round('1010ns')
|
||||
|
||||
def test_round_invalid_arg(self):
|
||||
stamp = Timestamp('2000-01-05 05:09:15.13')
|
||||
with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
|
||||
stamp.round('foo')
|
||||
|
||||
@pytest.mark.parametrize('test_input, rounder, freq, expected', [
|
||||
('2117-01-01 00:00:45', 'floor', '15s', '2117-01-01 00:00:45'),
|
||||
('2117-01-01 00:00:45', 'ceil', '15s', '2117-01-01 00:00:45'),
|
||||
('2117-01-01 00:00:45.000000012', 'floor', '10ns',
|
||||
'2117-01-01 00:00:45.000000010'),
|
||||
('1823-01-01 00:00:01.000000012', 'ceil', '10ns',
|
||||
'1823-01-01 00:00:01.000000020'),
|
||||
('1823-01-01 00:00:01', 'floor', '1s', '1823-01-01 00:00:01'),
|
||||
('1823-01-01 00:00:01', 'ceil', '1s', '1823-01-01 00:00:01'),
|
||||
('NaT', 'floor', '1s', 'NaT'),
|
||||
('NaT', 'ceil', '1s', 'NaT')
|
||||
])
|
||||
def test_ceil_floor_edge(self, test_input, rounder, freq, expected):
|
||||
dt = Timestamp(test_input)
|
||||
func = getattr(dt, rounder)
|
||||
result = func(freq)
|
||||
|
||||
if dt is NaT:
|
||||
assert result is NaT
|
||||
else:
|
||||
expected = Timestamp(expected)
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('test_input, freq, expected', [
|
||||
('2018-01-01 00:02:06', '2s', '2018-01-01 00:02:06'),
|
||||
('2018-01-01 00:02:00', '2T', '2018-01-01 00:02:00'),
|
||||
('2018-01-01 00:04:00', '4T', '2018-01-01 00:04:00'),
|
||||
('2018-01-01 00:15:00', '15T', '2018-01-01 00:15:00'),
|
||||
('2018-01-01 00:20:00', '20T', '2018-01-01 00:20:00'),
|
||||
('2018-01-01 03:00:00', '3H', '2018-01-01 03:00:00'),
|
||||
])
|
||||
@pytest.mark.parametrize('rounder', ['ceil', 'floor', 'round'])
|
||||
def test_round_minute_freq(self, test_input, freq, expected, rounder):
|
||||
# Ensure timestamps that shouldnt round dont!
|
||||
# GH#21262
|
||||
|
||||
dt = Timestamp(test_input)
|
||||
expected = Timestamp(expected)
|
||||
func = getattr(dt, rounder)
|
||||
result = func(freq)
|
||||
assert result == expected
|
||||
|
||||
def test_ceil(self):
|
||||
dt = Timestamp('20130101 09:10:11')
|
||||
result = dt.ceil('D')
|
||||
expected = Timestamp('20130102')
|
||||
assert result == expected
|
||||
|
||||
def test_floor(self):
|
||||
dt = Timestamp('20130101 09:10:11')
|
||||
result = dt.floor('D')
|
||||
expected = Timestamp('20130101')
|
||||
assert result == expected
|
||||
|
||||
@pytest.mark.parametrize('method', ['ceil', 'round', 'floor'])
|
||||
def test_round_dst_border_ambiguous(self, method):
|
||||
# GH 18946 round near "fall back" DST
|
||||
ts = Timestamp('2017-10-29 00:00:00', tz='UTC').tz_convert(
|
||||
'Europe/Madrid'
|
||||
)
|
||||
#
|
||||
result = getattr(ts, method)('H', ambiguous=True)
|
||||
assert result == ts
|
||||
|
||||
result = getattr(ts, method)('H', ambiguous=False)
|
||||
expected = Timestamp('2017-10-29 01:00:00', tz='UTC').tz_convert(
|
||||
'Europe/Madrid'
|
||||
)
|
||||
assert result == expected
|
||||
|
||||
result = getattr(ts, method)('H', ambiguous='NaT')
|
||||
assert result is NaT
|
||||
|
||||
with pytest.raises(pytz.AmbiguousTimeError):
|
||||
getattr(ts, method)('H', ambiguous='raise')
|
||||
|
||||
@pytest.mark.parametrize('method, ts_str, freq', [
|
||||
['ceil', '2018-03-11 01:59:00-0600', '5min'],
|
||||
['round', '2018-03-11 01:59:00-0600', '5min'],
|
||||
['floor', '2018-03-11 03:01:00-0500', '2H']])
|
||||
def test_round_dst_border_nonexistent(self, method, ts_str, freq):
|
||||
# GH 23324 round near "spring forward" DST
|
||||
ts = Timestamp(ts_str, tz='America/Chicago')
|
||||
result = getattr(ts, method)(freq, nonexistent='shift_forward')
|
||||
expected = Timestamp('2018-03-11 03:00:00', tz='America/Chicago')
|
||||
assert result == expected
|
||||
|
||||
result = getattr(ts, method)(freq, nonexistent='NaT')
|
||||
assert result is NaT
|
||||
|
||||
with pytest.raises(pytz.NonExistentTimeError,
|
||||
match='2018-03-11 02:00:00'):
|
||||
getattr(ts, method)(freq, nonexistent='raise')
|
||||
|
||||
@pytest.mark.parametrize('timestamp', [
|
||||
'2018-01-01 0:0:0.124999360',
|
||||
'2018-01-01 0:0:0.125000367',
|
||||
'2018-01-01 0:0:0.125500',
|
||||
'2018-01-01 0:0:0.126500',
|
||||
'2018-01-01 12:00:00',
|
||||
'2019-01-01 12:00:00',
|
||||
])
|
||||
@pytest.mark.parametrize('freq', [
|
||||
'2ns', '3ns', '4ns', '5ns', '6ns', '7ns',
|
||||
'250ns', '500ns', '750ns',
|
||||
'1us', '19us', '250us', '500us', '750us',
|
||||
'1s', '2s', '3s',
|
||||
'1D',
|
||||
])
|
||||
def test_round_int64(self, timestamp, freq):
|
||||
"""check that all rounding modes are accurate to int64 precision
|
||||
see GH#22591
|
||||
"""
|
||||
dt = Timestamp(timestamp)
|
||||
unit = to_offset(freq).nanos
|
||||
|
||||
# test floor
|
||||
result = dt.floor(freq)
|
||||
assert result.value % unit == 0, "floor not a {} multiple".format(freq)
|
||||
assert 0 <= dt.value - result.value < unit, "floor error"
|
||||
|
||||
# test ceil
|
||||
result = dt.ceil(freq)
|
||||
assert result.value % unit == 0, "ceil not a {} multiple".format(freq)
|
||||
assert 0 <= result.value - dt.value < unit, "ceil error"
|
||||
|
||||
# test round
|
||||
result = dt.round(freq)
|
||||
assert result.value % unit == 0, "round not a {} multiple".format(freq)
|
||||
assert abs(result.value - dt.value) <= unit // 2, "round error"
|
||||
if unit % 2 == 0 and abs(result.value - dt.value) == unit // 2:
|
||||
# round half to even
|
||||
assert result.value // unit % 2 == 0, "round half to even error"
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# Timestamp.replace
|
||||
|
||||
def test_replace_naive(self):
|
||||
# GH#14621, GH#7825
|
||||
ts = Timestamp('2016-01-01 09:00:00')
|
||||
result = ts.replace(hour=0)
|
||||
expected = Timestamp('2016-01-01 00:00:00')
|
||||
assert result == expected
|
||||
|
||||
def test_replace_aware(self, tz_aware_fixture):
|
||||
tz = tz_aware_fixture
|
||||
# GH#14621, GH#7825
|
||||
# replacing datetime components with and w/o presence of a timezone
|
||||
ts = Timestamp('2016-01-01 09:00:00', tz=tz)
|
||||
result = ts.replace(hour=0)
|
||||
expected = Timestamp('2016-01-01 00:00:00', tz=tz)
|
||||
assert result == expected
|
||||
|
||||
def test_replace_preserves_nanos(self, tz_aware_fixture):
|
||||
tz = tz_aware_fixture
|
||||
# GH#14621, GH#7825
|
||||
ts = Timestamp('2016-01-01 09:00:00.000000123', tz=tz)
|
||||
result = ts.replace(hour=0)
|
||||
expected = Timestamp('2016-01-01 00:00:00.000000123', tz=tz)
|
||||
assert result == expected
|
||||
|
||||
def test_replace_multiple(self, tz_aware_fixture):
|
||||
tz = tz_aware_fixture
|
||||
# GH#14621, GH#7825
|
||||
# replacing datetime components with and w/o presence of a timezone
|
||||
# test all
|
||||
ts = Timestamp('2016-01-01 09:00:00.000000123', tz=tz)
|
||||
result = ts.replace(year=2015, month=2, day=2, hour=0, minute=5,
|
||||
second=5, microsecond=5, nanosecond=5)
|
||||
expected = Timestamp('2015-02-02 00:05:05.000005005', tz=tz)
|
||||
assert result == expected
|
||||
|
||||
def test_replace_invalid_kwarg(self, tz_aware_fixture):
|
||||
tz = tz_aware_fixture
|
||||
# GH#14621, GH#7825
|
||||
ts = Timestamp('2016-01-01 09:00:00.000000123', tz=tz)
|
||||
with pytest.raises(TypeError):
|
||||
ts.replace(foo=5)
|
||||
|
||||
def test_replace_integer_args(self, tz_aware_fixture):
|
||||
tz = tz_aware_fixture
|
||||
# GH#14621, GH#7825
|
||||
ts = Timestamp('2016-01-01 09:00:00.000000123', tz=tz)
|
||||
with pytest.raises(ValueError):
|
||||
ts.replace(hour=0.1)
|
||||
|
||||
def test_replace_tzinfo_equiv_tz_localize_none(self):
|
||||
# GH#14621, GH#7825
|
||||
# assert conversion to naive is the same as replacing tzinfo with None
|
||||
ts = Timestamp('2013-11-03 01:59:59.999999-0400', tz='US/Eastern')
|
||||
assert ts.tz_localize(None) == ts.replace(tzinfo=None)
|
||||
|
||||
@td.skip_if_windows
|
||||
def test_replace_tzinfo(self):
|
||||
# GH#15683
|
||||
dt = datetime(2016, 3, 27, 1)
|
||||
tzinfo = pytz.timezone('CET').localize(dt, is_dst=False).tzinfo
|
||||
|
||||
result_dt = dt.replace(tzinfo=tzinfo)
|
||||
result_pd = Timestamp(dt).replace(tzinfo=tzinfo)
|
||||
|
||||
if PY3:
|
||||
# datetime.timestamp() converts in the local timezone
|
||||
with tm.set_timezone('UTC'):
|
||||
assert result_dt.timestamp() == result_pd.timestamp()
|
||||
|
||||
assert result_dt == result_pd
|
||||
assert result_dt == result_pd.to_pydatetime()
|
||||
|
||||
result_dt = dt.replace(tzinfo=tzinfo).replace(tzinfo=None)
|
||||
result_pd = Timestamp(dt).replace(tzinfo=tzinfo).replace(tzinfo=None)
|
||||
|
||||
if PY3:
|
||||
# datetime.timestamp() converts in the local timezone
|
||||
with tm.set_timezone('UTC'):
|
||||
assert result_dt.timestamp() == result_pd.timestamp()
|
||||
|
||||
assert result_dt == result_pd
|
||||
assert result_dt == result_pd.to_pydatetime()
|
||||
|
||||
@pytest.mark.parametrize('tz, normalize', [
|
||||
(pytz.timezone('US/Eastern'), lambda x: x.tzinfo.normalize(x)),
|
||||
(gettz('US/Eastern'), lambda x: x)])
|
||||
def test_replace_across_dst(self, tz, normalize):
|
||||
# GH#18319 check that 1) timezone is correctly normalized and
|
||||
# 2) that hour is not incorrectly changed by this normalization
|
||||
ts_naive = Timestamp('2017-12-03 16:03:30')
|
||||
ts_aware = conversion.localize_pydatetime(ts_naive, tz)
|
||||
|
||||
# Preliminary sanity-check
|
||||
assert ts_aware == normalize(ts_aware)
|
||||
|
||||
# Replace across DST boundary
|
||||
ts2 = ts_aware.replace(month=6)
|
||||
|
||||
# Check that `replace` preserves hour literal
|
||||
assert (ts2.hour, ts2.minute) == (ts_aware.hour, ts_aware.minute)
|
||||
|
||||
# Check that post-replace object is appropriately normalized
|
||||
ts2b = normalize(ts2)
|
||||
assert ts2 == ts2b
|
||||
|
||||
def test_replace_dst_border(self):
|
||||
# Gh 7825
|
||||
t = Timestamp('2013-11-3', tz='America/Chicago')
|
||||
result = t.replace(hour=3)
|
||||
expected = Timestamp('2013-11-3 03:00:00', tz='America/Chicago')
|
||||
assert result == expected
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# Timestamp.normalize
|
||||
|
||||
@pytest.mark.parametrize('arg', ['2013-11-30', '2013-11-30 12:00:00'])
|
||||
def test_normalize(self, tz_naive_fixture, arg):
|
||||
tz = tz_naive_fixture
|
||||
ts = Timestamp(arg, tz=tz)
|
||||
result = ts.normalize()
|
||||
expected = Timestamp('2013-11-30', tz=tz)
|
||||
assert result == expected
|
||||
|
||||
# --------------------------------------------------------------
|
||||
|
||||
@td.skip_if_windows
|
||||
def test_timestamp(self):
|
||||
# GH#17329
|
||||
# tz-naive --> treat it as if it were UTC for purposes of timestamp()
|
||||
ts = Timestamp.now()
|
||||
uts = ts.replace(tzinfo=utc)
|
||||
assert ts.timestamp() == uts.timestamp()
|
||||
|
||||
tsc = Timestamp('2014-10-11 11:00:01.12345678', tz='US/Central')
|
||||
utsc = tsc.tz_convert('UTC')
|
||||
|
||||
# utsc is a different representation of the same time
|
||||
assert tsc.timestamp() == utsc.timestamp()
|
||||
|
||||
if PY3:
|
||||
# datetime.timestamp() converts in the local timezone
|
||||
with tm.set_timezone('UTC'):
|
||||
# should agree with datetime.timestamp method
|
||||
dt = ts.to_pydatetime()
|
||||
assert dt.timestamp() == ts.timestamp()
|
||||
Reference in New Issue
Block a user