Skip to content

Commit 4eb91f4

Browse files
Chang Shewesm
Chang She
authored andcommitted
ENH: tz_convert for DataFrame #1330
1 parent 3f9bff6 commit 4eb91f4

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

pandas/core/generic.py

+36
Original file line numberDiff line numberDiff line change
@@ -858,6 +858,42 @@ def take(self, indices, axis=0):
858858
new_data = self._data.take(indices, axis=axis)
859859
return self._constructor(new_data)
860860

861+
def tz_convert(self, tz, axis=0, copy=True):
862+
"""
863+
Convert TimeSeries to target time zone. If it is time zone naive, it
864+
will be localized to the passed time zone.
865+
866+
Parameters
867+
----------
868+
tz : string or pytz.timezone object
869+
copy : boolean, default True
870+
Also make a copy of the underlying data
871+
872+
Returns
873+
-------
874+
"""
875+
axis = self._get_axis_number(axis)
876+
ax = self._get_axis(axis)
877+
878+
if not hasattr(ax, 'tz_convert'):
879+
ax_name = self._get_axis_name(axis)
880+
raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' %
881+
ax_name)
882+
883+
new_data = self._data
884+
if copy:
885+
new_data = new_data.copy()
886+
887+
new_obj = self._constructor(new_data)
888+
new_ax = ax.tz_convert(tz)
889+
890+
if axis == 0:
891+
new_obj._set_axis(1, new_ax)
892+
elif axis == 1:
893+
new_obj._set_axis(0, new_ax)
894+
895+
return new_obj
896+
861897
# Good for either Series or DataFrame
862898

863899
def truncate(self, before=None, after=None, copy=True):

pandas/tseries/tests/test_timezones.py

+12
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,18 @@ def test_tz_convert(self):
277277
result = ts.tz_convert('utc')
278278
self.assert_(result.index.tz.zone == 'UTC')
279279

280+
df = DataFrame({'a': 1}, index=rng)
281+
result = df.tz_convert('utc')
282+
expected = DataFrame({'a': 1}, rng.tz_convert('UTC'))
283+
self.assert_(result.index.tz.zone == 'UTC')
284+
assert_frame_equal(result, expected)
285+
foo
286+
287+
df = df.T
288+
result = df.tz_convert('utc', axis=1)
289+
self.assert_(result.columns.tz.zone == 'UTC')
290+
assert_frame_equal(result, expected.T)
291+
280292
def test_join_utc_convert(self):
281293
rng = date_range('1/1/2011', periods=100, freq='H', tz='utc')
282294

0 commit comments

Comments
 (0)