From 2b6dfec1cccee1d9aa91d986cebcaa5d651438c7 Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Mon, 28 Apr 2003 21:30:13 +0000 Subject: [PATCH] Raise a ValueError when there is data that was not covered in the format string. Done to match behavior of pre-existing C-based strptime implementations. --- Lib/_strptime.py | 3 +++ Lib/test/test_strptime.py | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/Lib/_strptime.py b/Lib/_strptime.py index 81c105f758d..4b7a7dd6151 100644 --- a/Lib/_strptime.py +++ b/Lib/_strptime.py @@ -423,6 +423,9 @@ def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): found = format_regex.match(data_string) if not found: raise ValueError("time data did not match format") + if len(data_string) != found.end(): + raise ValueError("unconverted data remains: %s" % + data_string[found.end():]) year = 1900 month = day = 1 hour = minute = second = 0 diff --git a/Lib/test/test_strptime.py b/Lib/test/test_strptime.py index a106a4289da..2c3955b4a3b 100644 --- a/Lib/test/test_strptime.py +++ b/Lib/test/test_strptime.py @@ -227,6 +227,10 @@ class StrptimeTests(unittest.TestCase): self.assertRaises(ValueError, _strptime.strptime, data_string="%d", format="%A") + def test_unconverteddata(self): + # Check ValueError is raised when there is unconverted data + self.assertRaises(ValueError, _strptime.strptime, "10 12", "%m") + def helper(self, directive, position): """Helper fxn in testing.""" strf_output = time.strftime("%" + directive, self.time_tuple)