Skip to content

Add test for GH 18523 and add _tz_compare() to compare timezone of DatetimeIndex #18596

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
26 changes: 24 additions & 2 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,28 @@ def join(self, other, how='left', level=None, return_indexers=False,
return Index.join(this, other, how=how, level=level,
return_indexers=return_indexers, sort=sort)

def _tz_compare(self, other):
"""
Compare string representations of timezones of two DatetimeIndex as
directly comparing equality is broken. The same timezone can be
represented as different instances of timezones. For example
`<DstTzInfo 'Europe/Paris' LMT+0:09:00 STD>` and
`<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>` are essentially same
timezones but aren't evaluted such, but the string representation
for both of these is `'Europe/Paris'`.

Parameters
----------
other: DatetimeIndex

Returns:
-------
compare : Boolean

"""
# GH 18523
return str(self.tzinfo) == str(other.tzinfo)

def _maybe_utc_convert(self, other):
this = self
if isinstance(other, DatetimeIndex):
Expand All @@ -1138,7 +1160,7 @@ def _maybe_utc_convert(self, other):
raise TypeError('Cannot join tz-naive with tz-aware '
'DatetimeIndex')

if self.tz != other.tz:
if not self._tz_compare(other):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you also add for all the other cases of str(self.tz) != str(other) (or variants on this)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other places where pandas uses variants for str(self.tz) != str(other.tz) isn't particularly for DatetimeIndex. For example in test_timezones.py this is used to test the equality of Timestamp I guess we have to write a more general method which takes in any object with a .tz attribute and compare it. In that case which file should I put this method in?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the right place to put this is in
pandas/_libs/tslibs/timezones.pyx

and just call it from where needed

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI - I added an additional instance of this in a commit that went in earlier today. Current location on master:

elif (isinstance(left, ABCDatetimeIndex) and
str(left.tz) != str(right.tz)):

this = self.tz_convert('UTC')
other = other.tz_convert('UTC')
return this, other
Expand Down Expand Up @@ -1243,7 +1265,7 @@ def __iter__(self):

def _wrap_union_result(self, other, result):
name = self.name if self.name == other.name else None
if self.tz != other.tz:
if not self._tz_compare(other):
raise ValueError('Passed item and index have different timezone')
return self._simple_new(result, name=name, freq=None, tz=self.tz)

Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/indexes/datetimes/test_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,26 @@ def test_000constructor_resolution(self):

assert idx.nanosecond[0] == t1.nanosecond

def test_concat(self):
idx1 = pd.date_range('2011-01-01', periods=3, freq='H',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pls add the issue number as a comment

tz='Europe/Paris')
idx2 = pd.date_range(start=idx1[0], end=idx1[-1], freq='H')
df1 = pd.DataFrame({'a': [1, 2, 3]}, index=idx1)
df2 = pd.DataFrame({'b': [1, 2, 3]}, index=idx2)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you move this to pandas/tests/reshape/test_concat.py

res = pd.concat([df1, df2], axis=1)

assert str(res.index.tzinfo) == str(df1.index.tzinfo)
assert str(res.index.tzinfo) == str(df2.index.tzinfo)

idx3 = pd.date_range('2011-01-01', periods=3,
freq='H', tz='Asia/Tokyo')
df3 = pd.DataFrame({'b': [1, 2, 3]}, index=idx3)
res = pd.concat([df1, df3], axis=1)

assert str(res.index.tzinfo) == 'UTC'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of this, can you construct the expected frame directly and use
tm.assert_frame_equal (same as above as well)

assert str(res.index.tzinfo) != str(df1.index.tzinfo)
assert str(res.index.tzinfo) != str(df3.index.tzinfo)


class TestTimeSeries(object):

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/datetimes/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,7 @@ def test_to_datetime_freq(self):
xp = bdate_range('2000-1-1', periods=10, tz='UTC')
rs = xp.to_datetime()
assert xp.freq == rs.freq
assert xp.tzinfo == rs.tzinfo
assert xp._tz_compare(rs)

def test_to_datetime_overflow(self):
# gh-17637
Expand Down
39 changes: 39 additions & 0 deletions pandas/tests/reshape/test_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1959,6 +1959,45 @@ def test_concat_order(self):
expected = expected.sort_values()
tm.assert_index_equal(result, expected)

def test_concat_datetime_timezone(self):
# GH 18523
idx1 = pd.date_range('2011-01-01', periods=3, freq='H',
tz='Europe/Paris')
idx2 = pd.date_range(start=idx1[0], end=idx1[-1], freq='H')
df1 = pd.DataFrame({'a': [1, 2, 3]}, index=idx1)
df2 = pd.DataFrame({'b': [1, 2, 3]}, index=idx2)
res = pd.concat([df1, df2], axis=1)

exp_idx = DatetimeIndex(['2011-01-01 00:00:00+01:00',
'2011-01-01 01:00:00+01:00',
'2011-01-01 02:00:00+01:00'],
freq='H'
).tz_localize('UTC').tz_convert('Europe/Paris')

exp = pd.DataFrame([[1, 1], [2, 2], [3, 3]],
index=exp_idx, columns=['a', 'b'])

tm.assert_frame_equal(res, exp)

idx3 = pd.date_range('2011-01-01', periods=3,
freq='H', tz='Asia/Tokyo')
df3 = pd.DataFrame({'b': [1, 2, 3]}, index=idx3)
res = pd.concat([df1, df3], axis=1)

exp_idx = DatetimeIndex(['2010-12-31 15:00:00+00:00',
'2010-12-31 16:00:00+00:00',
'2010-12-31 17:00:00+00:00',
'2010-12-31 23:00:00+00:00',
'2011-01-01 00:00:00+00:00',
'2011-01-01 01:00:00+00:00']
).tz_localize('UTC')

exp = pd.DataFrame([[np.nan, 1], [np.nan, 2], [np.nan, 3],
[1, np.nan], [2, np.nan], [3, np.nan]],
index=exp_idx, columns=['a', 'b'])

tm.assert_frame_equal(res, exp)


@pytest.mark.parametrize('pdt', [pd.Series, pd.DataFrame, pd.Panel])
@pytest.mark.parametrize('dt', np.sctypes['float'])
Expand Down