Skip to content

Commit cc1c642

Browse files
committed
Fix from_format() trying to parse escaped tokens
1 parent 0e66bcb commit cc1c642

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- Fixed missing `x` token for string formatting.
99
- Fixed reading timezone files.
1010
- Added support for parsing padded 2-digit days of the month with `from_format()`
11+
- Fixed `from_format()` trying to parse escaped tokens.
1112

1213

1314
## [2.0.3] - 2018-07-30

pendulum/formatting/formatter.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ class Formatter:
5858

5959
_FORMAT_RE = re.compile(_TOKENS)
6060

61+
_FROM_FORMAT_RE = re.compile(r"(?<!\\\[)" + _TOKENS + r"(?!\\\])")
62+
6163
_LOCALIZABLE_TOKENS = {
6264
"Qo": None,
6365
"MMMM": "months.wide",
@@ -372,7 +374,7 @@ def parse(
372374
"""
373375
escaped_fmt = re.escape(fmt)
374376

375-
tokens = self._FORMAT_RE.findall(escaped_fmt)
377+
tokens = self._FROM_FORMAT_RE.findall(escaped_fmt)
376378
if not tokens:
377379
return time
378380

@@ -397,7 +399,7 @@ def parse(
397399
"timestamp": None,
398400
}
399401

400-
pattern = self._FORMAT_RE.sub(
402+
pattern = self._FROM_FORMAT_RE.sub(
401403
lambda m: self._replace_tokens(m.group(0), locale), escaped_fmt
402404
)
403405

tests/datetime/test_from_format.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ def test_from_format_with_escaped_elements():
3737
assert "+00:00" == d.timezone_name
3838

3939

40+
def test_from_format_with_escaped_elements_valid_tokens():
41+
d = pendulum.from_format("1975-05-21T22:32:11.123Z", "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")
42+
assert_datetime(d, 1975, 5, 21, 22, 32, 11)
43+
assert "UTC" == d.timezone_name
44+
45+
4046
def test_from_format_with_millis():
4147
d = pendulum.from_format("1975-05-21 22:32:11.123456", "YYYY-MM-DD HH:mm:ss.SSSSSS")
4248
assert_datetime(d, 1975, 5, 21, 22, 32, 11, 123456)

0 commit comments

Comments
 (0)