]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-43295: Fix error handling of datetime.strptime format string '%z' (GH-24627)...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 20 May 2021 00:37:49 +0000 (17:37 -0700)
committerGitHub <noreply@github.com>
Thu, 20 May 2021 00:37:49 +0000 (20:37 -0400)
Previously, `datetime.strptime` would match `'z'` with the format string `'%z'` (for UTC offsets), throwing an `IndexError` by erroneously trying to parse `'z'` as a timestamp. As a special case, `'%z'` matches the string `'Z'` which is equivalent to the offset `'+00:00'`, however this behavior is not defined for lowercase `'z'`.

This change ensures a `ValueError` is thrown when encountering the original example, as follows:

```
>>> from datetime import datetime
>>> datetime.strptime('z', '%z')
ValueError: time data 'z' does not match format '%z'
```

Automerge-Triggered-By: GH:pganssle
(cherry picked from commit 04f6fbb6969e9860783b9ab4dc24b6fe3c6dab8d)

Co-authored-by: Noor Michael <nsmichael31@gmail.com>
Co-authored-by: Noor Michael <nsmichael31@gmail.com>
Lib/_strptime.py
Lib/test/datetimetester.py
Misc/NEWS.d/next/Library/2021-02-22-22-54-40.bpo-43295.h_ffu7.rst [new file with mode: 0644]

index 5df37f5f4b89d5c7e7bbcdc5b986c3208c36c5cc..b97dfcce1e8e4d7dfe2eb8c3a22f2f9b7536c78b 100644 (file)
@@ -201,7 +201,7 @@ class TimeRE(dict):
             #XXX: Does 'Y' need to worry about having less or more than
             #     4 digits?
             'Y': r"(?P<Y>\d\d\d\d)",
-            'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|Z)",
+            'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|(?-i:Z))",
             'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
             'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
             'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
index b37ef9170787237f64fa67f6df4c54aa1af32818..a9c3a370e0e838a11710ce049c65ef39f10ef335 100644 (file)
@@ -2609,6 +2609,7 @@ class TestDateTime(TestDate):
 
         with self.assertRaises(ValueError): strptime("-2400", "%z")
         with self.assertRaises(ValueError): strptime("-000", "%z")
+        with self.assertRaises(ValueError): strptime("z", "%z")
 
     def test_strptime_single_digit(self):
         # bpo-34903: Check that single digit dates and times are allowed.
diff --git a/Misc/NEWS.d/next/Library/2021-02-22-22-54-40.bpo-43295.h_ffu7.rst b/Misc/NEWS.d/next/Library/2021-02-22-22-54-40.bpo-43295.h_ffu7.rst
new file mode 100644 (file)
index 0000000..ac9a5c9
--- /dev/null
@@ -0,0 +1,2 @@
+:meth:`datetime.datetime.strptime` now raises ``ValueError`` instead of
+``IndexError`` when matching ``'z'`` with the ``%z`` format specifier.