diff --git a/src/pendulum/duration.py b/src/pendulum/duration.py index a4875fca..074ae5e4 100644 --- a/src/pendulum/duration.py +++ b/src/pendulum/duration.py @@ -238,7 +238,12 @@ def in_minutes(self) -> int: def in_seconds(self) -> int: return int(self.total_seconds()) - def in_words(self, locale: str | None = None, separator: str = " ") -> str: + def in_words( + self, + locale: str | None = None, + separator: str = " ", + seconds_n_decimal: int = 2, + ) -> str: """ Get the current interval in words in the current locale. @@ -246,6 +251,9 @@ def in_words(self, locale: str | None = None, separator: str = " ") -> str: :param locale: The locale to use. Defaults to current locale. :param separator: The separator to use between each unit + :param kwargs: Additional keyword arguments. + - seconds_n_decimal (int): The number of decimal places to use for seconds if no other time units are present. Defaults to 2. + """ intervals = [ ("year", self.years), @@ -273,9 +281,10 @@ def in_words(self, locale: str | None = None, separator: str = " ") -> str: if not parts: count: int | str = 0 - if abs(self.microseconds) > 0: - unit = f"units.second.{loaded_locale.plural(1)}" - count = f"{abs(self.microseconds) / 1e6:.2f}" + unit = f"units.second.{loaded_locale.plural(0)}" + if self.microseconds != 0: + microseconds = abs(self.microseconds) / 1e6 + count = str({round(microseconds, ndigits=seconds_n_decimal)}) else: unit = f"units.microsecond.{loaded_locale.plural(0)}" translation = loaded_locale.translation(unit) diff --git a/tests/duration/test_in_words.py b/tests/duration/test_in_words.py index c0a1a1fe..191ba844 100644 --- a/tests/duration/test_in_words.py +++ b/tests/duration/test_in_words.py @@ -62,12 +62,17 @@ def test_separator(): def test_subseconds(): pi = pendulum.duration(microseconds=123456) - assert pi.in_words() == "0.12 second" + assert pi.in_words() == "0.12 seconds" + + +def test_subseconds_with_n_digits(): + pi = pendulum.duration(microseconds=123456) + + assert pi.in_words(seconds_n_decimal=3) == "0.123 seconds" def test_subseconds_with_seconds(): pi = pendulum.duration(seconds=12, microseconds=123456) - assert pi.in_words() == "12 seconds"