Skip to content

Organize, Split, Parametrize timezones/timestamps tests #19473

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 1, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
570 changes: 27 additions & 543 deletions pandas/tests/scalar/test_timestamp.py

Large diffs are not rendered by default.

Empty file.
76 changes: 76 additions & 0 deletions pandas/tests/scalar/timestamp/test_arithmetic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta

import pytest
import numpy as np

from pandas.compat import long
from pandas.tseries import offsets
from pandas import Timestamp, Timedelta


class TestTimestampArithmetic(object):
def test_overflow_offset(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 = 20169940 * offsets.Day(1)

with pytest.raises(OverflowError):
stamp + offset

with pytest.raises(OverflowError):
offset + stamp

with pytest.raises(OverflowError):
stamp - offset

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')

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

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
193 changes: 193 additions & 0 deletions pandas/tests/scalar/timestamp/test_comparisons.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
# -*- coding: utf-8 -*-
import sys
from datetime import datetime
import operator

import pytest
import numpy as np

from dateutil.tz import tzutc
from pytz import utc

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):
# see gh-1404
a = Timestamp('3/12/2012')
b = Timestamp('3/12/2012', tz='utc')

pytest.raises(Exception, a.__eq__, b)
pytest.raises(Exception, a.__ne__, b)
pytest.raises(Exception, a.__lt__, b)
pytest.raises(Exception, a.__gt__, b)
pytest.raises(Exception, b.__eq__, a)
pytest.raises(Exception, b.__ne__, a)
pytest.raises(Exception, b.__lt__, a)
pytest.raises(Exception, b.__gt__, a)

if sys.version_info < (3, 3):
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
pytest.raises(Exception, a.to_pydatetime().__eq__, b)
else:
assert not a == b.to_pydatetime()
assert not a.to_pydatetime() == b

def test_cant_compare_tz_naive_w_aware_explicit_pytz(self):
# see gh-1404
a = Timestamp('3/12/2012')
b = Timestamp('3/12/2012', tz=utc)

pytest.raises(Exception, a.__eq__, b)
pytest.raises(Exception, a.__ne__, b)
pytest.raises(Exception, a.__lt__, b)
pytest.raises(Exception, a.__gt__, b)
pytest.raises(Exception, b.__eq__, a)
pytest.raises(Exception, b.__ne__, a)
pytest.raises(Exception, b.__lt__, a)
pytest.raises(Exception, b.__gt__, a)

if sys.version_info < (3, 3):
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
pytest.raises(Exception, a.to_pydatetime().__eq__, b)
else:
assert not a == b.to_pydatetime()
assert not a.to_pydatetime() == b

def test_cant_compare_tz_naive_w_aware_dateutil(self):
# see gh-1404
a = Timestamp('3/12/2012')
b = Timestamp('3/12/2012', tz=tzutc())

pytest.raises(Exception, a.__eq__, b)
pytest.raises(Exception, a.__ne__, b)
pytest.raises(Exception, a.__lt__, b)
pytest.raises(Exception, a.__gt__, b)
pytest.raises(Exception, b.__eq__, a)
pytest.raises(Exception, b.__ne__, a)
pytest.raises(Exception, b.__lt__, a)
pytest.raises(Exception, b.__gt__, a)

if sys.version_info < (3, 3):
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
pytest.raises(Exception, a.to_pydatetime().__eq__, 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 changes: 96 additions & 0 deletions pandas/tests/scalar/timestamp/test_rendering.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*-

import pytest
import dateutil
import pytz # noqa # a test below uses pytz but only inside a `eval` call

import pprint
from distutils.version import LooseVersion

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
Loading