Skip to content

Commit 04f6fbb

Browse files
authored
bpo-43295: Fix error handling of datetime.strptime format string '%z' (GH-24627)
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
1 parent 3b4b2cf commit 04f6fbb

File tree

3 files changed

+4
-1
lines changed

3 files changed

+4
-1
lines changed

Lib/_strptime.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ def __init__(self, locale_time=None):
201201
#XXX: Does 'Y' need to worry about having less or more than
202202
# 4 digits?
203203
'Y': r"(?P<Y>\d\d\d\d)",
204-
'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|Z)",
204+
'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|(?-i:Z))",
205205
'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
206206
'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
207207
'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),

Lib/test/datetimetester.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2609,6 +2609,7 @@ def test_strptime(self):
26092609

26102610
with self.assertRaises(ValueError): strptime("-2400", "%z")
26112611
with self.assertRaises(ValueError): strptime("-000", "%z")
2612+
with self.assertRaises(ValueError): strptime("z", "%z")
26122613

26132614
def test_strptime_single_digit(self):
26142615
# bpo-34903: Check that single digit dates and times are allowed.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:meth:`datetime.datetime.strptime` now raises ``ValueError`` instead of
2+
``IndexError`` when matching ``'z'`` with the ``%z`` format specifier.

0 commit comments

Comments
 (0)