Skip to content

Commit ad249df

Browse files
committed
BUG: DatetimeEngine does not handle pydatetime with tz #2575
1 parent 46b93ce commit ad249df

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

pandas/index.pyx

+15-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ from hashtable cimport *
1818
from . import algos, tslib, hashtable as _hash
1919
from .tslib import Timestamp
2020

21-
2221
from datetime cimport (get_datetime64_value, _pydatetime_to_dts,
2322
pandas_datetimestruct)
2423

@@ -30,6 +29,13 @@ cdef extern from "datetime.h":
3029

3130
cdef int64_t iNaT = util.get_nat()
3231

32+
try:
33+
from dateutil.tz import tzutc as _du_utc
34+
import pytz
35+
UTC = pytz.utc
36+
have_pytz = True
37+
except:
38+
have_pytz = False
3339

3440
PyDateTime_IMPORT
3541

@@ -497,6 +503,13 @@ cdef inline _to_i8(object val):
497503
if util.is_datetime64_object(val):
498504
return get_datetime64_value(val)
499505
elif PyDateTime_Check(val):
500-
return _pydatetime_to_dts(val, &dts)
506+
tzinfo = getattr(val, 'tzinfo', None)
507+
val = _pydatetime_to_dts(val, &dts)
508+
if tzinfo is not None and not _is_utc(tzinfo):
509+
offset = tslib._get_utcoffset(tzinfo, val)
510+
val -= tslib._delta_to_nanoseconds(offset)
511+
501512
return val
502513

514+
cdef inline bint _is_utc(object tz):
515+
return tz is UTC or isinstance(tz, _du_utc)

pandas/tseries/tests/test_timezones.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
import sys
44
import os
55
import unittest
6-
76
import nose
87

98
import numpy as np
9+
import pytz
1010

1111
from pandas import (Index, Series, TimeSeries, DataFrame, isnull,
1212
date_range, Timestamp)
@@ -558,6 +558,16 @@ def test_dateutil_tzoffset_support(self):
558558
# it works! #2443
559559
repr(series.index[0])
560560

561+
def test_getitem_pydatetime_tz(self):
562+
index = date_range(start='2012-12-24 16:00',
563+
end='2012-12-24 18:00', freq='H',
564+
tz='Europe/Berlin')
565+
ts = Series(index=index, data=index.hour)
566+
time_pandas = Timestamp('2012-12-24 17:00', tz='Europe/Berlin')
567+
time_datetime = datetime(2012,12,24,17,00,
568+
tzinfo=pytz.timezone('Europe/Berlin'))
569+
self.assertEqual(ts[time_pandas], ts[time_datetime])
570+
561571

562572
class TestTimeZones(unittest.TestCase):
563573
_multiprocess_can_split_ = True

0 commit comments

Comments
 (0)