akkudoktoreos.utils.datetimeutil.to_duration

akkudoktoreos.utils.datetimeutil.to_duration(input_value: Duration | timedelta | str | int | float | Tuple[int, int, int, int] | List[int], as_string: Literal[False] | None = None) Duration
akkudoktoreos.utils.datetimeutil.to_duration(input_value: Duration | timedelta | str | int | float | Tuple[int, int, int, int] | List[int], as_string: str | Literal[True] = True) str

Converts various input types into a pendulum.Duration or a formatted duration string.

Parameters:
  • input_value (Union[Duration, timedelta, str, int, float, tuple, list]) –

    The input value to convert into a duration. Supported types include:

    • pendulum.Duration: Returned unchanged unless formatting is requested.

    • datetime.timedelta: Converted based on total seconds.

    • str: A duration expression (e.g., “15 minutes”, “2 hours”), or a string parsed by Pendulum.

    • int or float: Interpreted as a number of seconds.

    • tuple or list: Must be (days, hours, minutes, seconds).

  • as_string (Optional[Union[str, bool]]) –

    Controls the output format of the returned duration:

    • None or False (default):

      Returns a pendulum.Duration object.

    • True:

      Returns an ISO-8601 duration string (e.g., “PT15M”).

    • ”human”:

      Returns a human-readable form (e.g., “15 minutes”).

    • ”pandas”:

      Returns a Pandas frequency string such as: - “1h” for 1 hour - “15min” for 15 minutes - “900s” for 900 seconds

    • str:

      A custom format pattern. The following format tokens are supported: - {S} → total seconds - {M} → total minutes (integer) - {H} → total hours (integer) - {f} → human-friendly representation (Pendulum in_words())

Example

“Duration: {M} minutes”“Duration: 15 minutes”

Returns:

  • A pendulum.Duration if no formatting is requested.

  • A formatted string depending on the as_string option.

Return type:

Union[Duration, str]

Raises:

ValueError

  • If the input type is unsupported. - If a duration string cannot be parsed. - If as_string contains an unsupported format option.

Examples

>>> to_duration("15 minutes")
<Duration [900 seconds]>
>>> to_duration("15 minutes", as_string=True)
'PT15M'
>>> to_duration("15 minutes", as_string="human")
'15 minutes'
>>> to_duration("90 seconds", as_string="pandas")
'90S'
>>> to_duration("15 minutes", as_string="{M}m")
'15m'