From bf27e62729f6bec33a9e7c3d754f6a69a3f93c64 Mon Sep 17 00:00:00 2001 From: 5j9 <5j9@users.noreply.github.com> Date: Wed, 29 Mar 2023 07:34:18 +0330 Subject: [PATCH] fix(strftime): also escape %% before c, x, and X --- jdatetime/__init__.py | 20 ++++++++++++-------- tests/test_jdatetime.py | 1 + 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/jdatetime/__init__.py b/jdatetime/__init__.py index c1242ee..81a288d 100644 --- a/jdatetime/__init__.py +++ b/jdatetime/__init__.py @@ -29,6 +29,7 @@ "%A": ("_strftime_get_method_value", {"attr": "jweekday", "fmt": "%s"}), "%b": ("_strftime_get_method_value", {"attr": "jmonth_short", "fmt": "%s"}), "%B": ("_strftime_get_method_value", {"attr": "jmonth", "fmt": "%s"}), + "%c": ("_strftime_c", {}), "%d": ("_strftime_get_attr_value", {"attr": "day", "fmt": "%02.d"}), "%-d": ("_strftime_get_attr_value", {"attr": "day", "fmt": "%d"}), "%j": ("_strftime_get_method_value", {"attr": "yday", "fmt": "%03.d"}), @@ -48,6 +49,8 @@ "%S": ("_strftime_get_attr_value", {"attr": "second", "fmt": "%02.d", "fb": "00"}), "%-S": ("_strftime_get_attr_value", {"attr": "second", "fmt": "%d", "fb": "0"}), "%p": ("_strftime_p", {}), + "%x": ("_strftime_x", {}), + "%X": ("_strftime_cap_x", {}), "%z": ("_strftime_z", {}), "%Z": ("_strftime_cap_z", {}), } @@ -630,6 +633,15 @@ def _strftime_cap_z(self): else: return '' + def _strftime_c(self): + return self.strftime("%a %b %d %H:%M:%S %Y") + + def _strftime_cap_x(self): + return self.strftime("%H:%M:%S") + + def _strftime_x(self): + return self.strftime("%m/%d/%y") + def strftime(self, format): # Convert to unicode try: @@ -637,14 +649,6 @@ def strftime(self, format): except Exception: pass - symbols = { - "%c": "%a %b %d %H:%M:%S %Y", - "%x": "%m/%d/%y", - "%X": "%H:%M:%S", - } - for s, r in symbols.items(): - format = format.replace(s, r) - def repl(match): symbol = match[0] if symbol in STRFTIME_MAPPING: diff --git a/tests/test_jdatetime.py b/tests/test_jdatetime.py index 7ff6162..1e248b6 100644 --- a/tests/test_jdatetime.py +++ b/tests/test_jdatetime.py @@ -237,6 +237,7 @@ def test_strftime_single_digit(self): def test_strftime_escape_percent(self): dt = jdatetime.datetime(1402, 1, 7) + self.assertEqual(dt.strftime("%%x=%x"), "%x=01/07/02") self.assertEqual(dt.strftime("%%d=%d"), "%d=07") self.assertEqual(dt.strftime("%%%d"), "%07")