Skip to content

Commit 2355579

Browse files
committed
python: support h suffix with !d conversion specifier
Problem: The `!d` conversion specifier converts timestamps to UtilDatetime objects which support a `::` separator in order to allow a format after the datetime format specification. However, since the format is applied within the UtilDatetime format() method, the `h` suffix is not supported to replace empty fields with a hyphen. Check for a `h` suffix in the UtilDatetime.format() method and replace an empty string with `-`. Ignore UtilDatetime objects where `h` is normally handled so that the suffix can later be processed in UtilDatetime.format()
1 parent bf96eac commit 2355579

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

src/bindings/python/flux/util.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -312,19 +312,28 @@ class UtilDatetime(datetime):
312312
def __format__(self, fmt):
313313
# The string "::" is used to split the strftime() format from
314314
# any Python format spec:
315-
vals = fmt.split("::", 1)
315+
timefmt, *spec = fmt.split("::", 1)
316316

317317
if self == datetime.fromtimestamp(0.0):
318318
result = ""
319319
else:
320320
# Call strftime() to get the formatted datetime as a string
321-
result = self.strftime(vals[0])
321+
result = self.strftime(timefmt)
322+
323+
spec = spec[0] if spec else ""
324+
325+
# Handling of the 'h' suffix on spec is required here, since the
326+
# UtilDatetime format() is called _after_ UtilFormatter.format_field()
327+
# (where this option is handled for other types)
328+
if spec.endswith("h"):
329+
if not result:
330+
result = "-"
331+
spec = spec[:-1] + "s"
322332

323333
# If there was a format spec, apply it here:
324-
try:
325-
return f"{{0:{vals[1]}}}".format(result)
326-
except IndexError:
327-
return result
334+
if spec:
335+
return f"{{0:{spec}}}".format(result)
336+
return result
328337

329338

330339
def fsd(secs):
@@ -424,7 +433,10 @@ def format_field(self, value, spec):
424433
denote_truncation = True
425434
spec = spec[:-1]
426435

427-
if spec.endswith("h"):
436+
# Note: handling of the 'h' suffix for UtilDatetime objects
437+
# must be deferred to the UtilDatetetime format() method, since
438+
# that method will be called after this one:
439+
if spec.endswith("h") and not isinstance(value, UtilDatetime):
428440
localepoch = datetime.fromtimestamp(0.0).strftime("%FT%T")
429441
basecases = ("", "0s", "0.0", "0:00:00", "1970-01-01T00:00:00", localepoch)
430442
value = "-" if str(value) in basecases else str(value)

0 commit comments

Comments
 (0)