bpo-43295: Fix error handling of datetime.strptime format string '%z' (GH-24627) (#25695)

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 04f6fbb696)

Co-authored-by: Noor Michael <nsmichael31@gmail.com>

Co-authored-by: Noor Michael <nsmichael31@gmail.com>
This commit is contained in:
Miss Islington (bot) 2021-05-19 17:37:49 -07:00 committed by GitHub
parent dc6526dfa2
commit c87b81dcb2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 4 additions and 1 deletions

View 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.