From 29e48907df7d3663fad43414fad774b10bae99d9 Mon Sep 17 00:00:00 2001 From: Kami Date: Sun, 2 Feb 2025 00:14:55 +0100 Subject: [PATCH] improved uptime calculation with fewer lines --- modules/utility.py | 56 +++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 30 deletions(-) diff --git a/modules/utility.py b/modules/utility.py index 5e0a69d..4d546b1 100644 --- a/modules/utility.py +++ b/modules/utility.py @@ -5,41 +5,37 @@ import json DICTIONARY_PATH = "dictionary/" # Path to dictionary files -def format_uptime(seconds: float) -> str: +def format_uptime(seconds: float) -> tuple[str, int]: """ Convert seconds into a human-readable string: - e.g. 32 minutes, 8 days, 8 months, etc. - Returns two values: - 1. Human-readable format - 2. Seconds since start + - Example outputs: + "32 minutes" + "8 days, 4 hours" + "1 year, 3 months" + - Returns a tuple: + (Human-readable string, total seconds) """ - # Convert float seconds to an integer - seconds = int(seconds) + seconds = int(seconds) # Ensure integer seconds - # We'll break it down - minutes, seconds = divmod(seconds, 60) - hours, minutes = divmod(minutes, 60) - days, hours = divmod(hours, 24) - # For months and years, let's approximate 30 days per month, - # 365 days per year, etc. (just a rough approach) - - months, days = divmod(days, 30) - years, months = divmod(months, 12) + # Define time units + units = [ + ("year", 31536000), # 365 days + ("month", 2592000), # 30 days + ("day", 86400), # 24 hours + ("hour", 3600), # 60 minutes + ("minute", 60), + ("second", 1) + ] - # Build a short string, only listing the largest units - # If you want more detail, you can keep going - if years > 0: - return [f"{years} year(s), {months} month(s)", seconds] - elif months > 0: - return [f"{months} month(s), {days} day(s)", seconds] - elif days > 0: - return [f"{days} day(s), {hours} hour(s)", seconds] - elif hours > 0: - return [f"{hours} hour(s), {minutes} minute(s)", seconds] - elif minutes > 0: - return [f"{minutes} minute(s)", seconds] - else: - return [f"{seconds} second(s)", seconds] + # Compute time breakdown + time_values = [] + for unit_name, unit_seconds in units: + value, seconds = divmod(seconds, unit_seconds) + if value > 0: + time_values.append(f"{value} {unit_name}{'s' if value > 1 else ''}") # Auto pluralize + + # Return only the **two most significant** time units (e.g., "3 days, 4 hours") + return (", ".join(time_values[:2]), seconds) if time_values else ("0 seconds", 0) def get_random_reply(dictionary_name: str, category: str, **variables) -> str: """