Skip to content

Commit 711ca84

Browse files
dannyi96YYYasin19
authored andcommitted
Added improvements in to_datetime Error reporting message - incorrect field today/now shown in error (pandas-dev#47860)
* Revert "addressing reviews CL#1" This reverts commit 69dc2d4. * Added improvements in to_datetime Error reporting message - incorrect field now/today shown as error * Added improvements in to_datetime Error reporting message - incorrect field now/today shown as error * added testcase * adding position info & updated testcase * precommit format changes * addressing review comments * addressing review comments * addressing review comments * addressing review comments * addressing review comments pandas-dev#2 * addressing review comments
1 parent 4515b89 commit 711ca84

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

pandas/_libs/tslib.pyx

+3-1
Original file line numberDiff line numberDiff line change
@@ -799,6 +799,7 @@ cdef _array_to_datetime_object(
799799
# We return an object array and only attempt to parse:
800800
# 1) NaT or NaT-like values
801801
# 2) datetime strings, which we return as datetime.datetime
802+
# 3) special strings - "now" & "today"
802803
for i in range(n):
803804
val = values[i]
804805
if checknull_with_nat_and_na(val) or PyDateTime_Check(val):
@@ -817,7 +818,8 @@ cdef _array_to_datetime_object(
817818
yearfirst=yearfirst)
818819
pydatetime_to_dt64(oresult[i], &dts)
819820
check_dts_bounds(&dts)
820-
except (ValueError, OverflowError):
821+
except (ValueError, OverflowError) as ex:
822+
ex.args = (f"{ex} present at position {i}", )
821823
if is_coerce:
822824
oresult[i] = <object>NaT
823825
continue

pandas/_libs/tslibs/parsing.pyx

+8
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,14 @@ def parse_datetime_string(
298298
if dt is not None:
299299
return dt
300300

301+
# Handling special case strings today & now
302+
if date_string == "now":
303+
dt = datetime.now()
304+
return dt
305+
elif date_string == "today":
306+
dt = datetime.today()
307+
return dt
308+
301309
try:
302310
dt, _ = _parse_dateabbr_string(date_string, _DEFAULT_DATETIME, freq=None)
303311
return dt

pandas/tests/tools/test_to_datetime.py

+7
Original file line numberDiff line numberDiff line change
@@ -2591,6 +2591,13 @@ def test_invalid_origins_tzinfo(self):
25912591
with pytest.raises(ValueError, match="must be tz-naive"):
25922592
to_datetime(1, unit="D", origin=datetime(2000, 1, 1, tzinfo=pytz.utc))
25932593

2594+
def test_incorrect_value_exception(self):
2595+
# GH47495
2596+
with pytest.raises(
2597+
ValueError, match="Unknown string format: yesterday present at position 1"
2598+
):
2599+
to_datetime(["today", "yesterday"])
2600+
25942601
@pytest.mark.parametrize("format", [None, "%Y-%m-%d %H:%M:%S"])
25952602
def test_to_datetime_out_of_bounds_with_format_arg(self, format):
25962603
# see gh-23830

0 commit comments

Comments
 (0)