Skip to content

Commit b2b9388

Browse files
committed
BUG: fix broken UTC localization, add tz_localize method to Timestamp, close #1397
1 parent cbc8b79 commit b2b9388

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

pandas/src/datetime.pyx

+24-3
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,24 @@ class Timestamp(_Timestamp):
165165
def asm8(self):
166166
return np.int64(self.value).view('M8[ns]')
167167

168+
def tz_localize(self, tz):
169+
"""
170+
Convert naive Timestamp to local time zone
171+
172+
Parameters
173+
----------
174+
tz : pytz.timezone
175+
176+
Returns
177+
-------
178+
localized : Timestamp
179+
"""
180+
if self.tzinfo is None:
181+
# tz naive, localize
182+
return Timestamp(self.to_pydatetime(), tz=tz)
183+
else:
184+
raise Exception('Cannot localize tz-aware Timestamp')
185+
168186
def tz_convert(self, tz):
169187
"""
170188
Convert Timestamp to another time zone or localize to requested time
@@ -445,12 +463,15 @@ cpdef convert_to_tsobject(object ts, object tz=None):
445463
# sort of a temporary hack
446464
if ts.tzinfo is not None:
447465
ts = tz.normalize(ts)
466+
obj.value = _pydatetime_to_dts(ts, &obj.dts)
448467
elif tz is not pytz.utc:
449468
ts = tz.localize(ts)
450-
451-
obj.value = _pydatetime_to_dts(ts, &obj.dts)
469+
obj.value = _pydatetime_to_dts(ts, &obj.dts)
470+
obj.value -= _delta_to_nanoseconds(ts.tzinfo._utcoffset)
471+
else:
472+
# UTC
473+
obj.value = _pydatetime_to_dts(ts, &obj.dts)
452474
obj.tzinfo = ts.tzinfo
453-
obj.value -= _delta_to_nanoseconds(obj.tzinfo._utcoffset)
454475
else:
455476
obj.value = _pydatetime_to_dts(ts, &obj.dts)
456477
obj.tzinfo = ts.tzinfo

pandas/tseries/tests/test_timeseries.py

+3
Original file line numberDiff line numberDiff line change
@@ -1507,6 +1507,9 @@ def test_create_with_tz(self):
15071507

15081508
self.assertEquals(stamp, rng[1])
15091509

1510+
utc_stamp = Timestamp('3/11/2012 05:00', tz='utc')
1511+
self.assertEquals(utc_stamp.hour, 5)
1512+
15101513
def test_tz_convert_localize(self):
15111514
stamp = Timestamp('3/11/2012 04:00')
15121515

0 commit comments

Comments
 (0)