Skip to content

Commit 1a70843

Browse files
committed
ENH: optimization on possibily_convert_datetime to only try conversion in certain cases
1 parent 42073a8 commit 1a70843

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

pandas/core/common.py

+25-18
Original file line numberDiff line numberDiff line change
@@ -955,10 +955,10 @@ def _possibly_cast_to_timedelta(value, coerce=True):
955955
def _possibly_cast_to_datetime(value, dtype, coerce = False):
956956
""" try to cast the array/value to a datetimelike dtype, converting float nan to iNaT """
957957

958-
if isinstance(dtype, basestring):
959-
dtype = np.dtype(dtype)
960-
961958
if dtype is not None:
959+
if isinstance(dtype, basestring):
960+
dtype = np.dtype(dtype)
961+
962962
is_datetime64 = is_datetime64_dtype(dtype)
963963
is_timedelta64 = is_timedelta64_dtype(dtype)
964964

@@ -984,21 +984,28 @@ def _possibly_cast_to_datetime(value, dtype, coerce = False):
984984
except:
985985
pass
986986

987-
elif dtype is None:
988-
# we might have a array (or single object) that is datetime like, and no dtype is passed
989-
# don't change the value unless we find a datetime set
990-
v = value
991-
if not is_list_like(v):
992-
v = [ v ]
993-
if len(v):
994-
inferred_type = lib.infer_dtype(v)
995-
if inferred_type == 'datetime':
996-
try:
997-
value = tslib.array_to_datetime(np.array(v))
998-
except:
999-
pass
1000-
elif inferred_type == 'timedelta':
1001-
value = _possibly_cast_to_timedelta(value)
987+
else:
988+
989+
# only do this if we have an array and the dtype of the array is not setup already
990+
# we are not an integer/object, so don't bother with this conversion
991+
if isinstance(value, np.ndarray) and not (issubclass(value.dtype.type, np.integer) or value.dtype == np.object_):
992+
pass
993+
994+
else:
995+
# we might have a array (or single object) that is datetime like, and no dtype is passed
996+
# don't change the value unless we find a datetime set
997+
v = value
998+
if not is_list_like(v):
999+
v = [ v ]
1000+
if len(v):
1001+
inferred_type = lib.infer_dtype(v)
1002+
if inferred_type == 'datetime':
1003+
try:
1004+
value = tslib.array_to_datetime(np.array(v))
1005+
except:
1006+
pass
1007+
elif inferred_type == 'timedelta':
1008+
value = _possibly_cast_to_timedelta(value)
10021009

10031010
return value
10041011

0 commit comments

Comments
 (0)