Skip to content

Pluralization bug with Duration.in_words() #826

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/pendulum/duration.py
Original file line number Diff line number Diff line change
@@ -238,14 +238,22 @@ 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.
Ex: 6 jours 23 heures 58 minutes
: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)
9 changes: 7 additions & 2 deletions tests/duration/test_in_words.py
Original file line number Diff line number Diff line change
@@ -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"