49 lines
1.7 KiB
Python
49 lines
1.7 KiB
Python
from datetime import timedelta
|
|
from typing import Optional
|
|
|
|
def format_human_readable_time(seconds: float) -> str:
|
|
"""
|
|
Convert seconds to human-readable time format using datetime.timedelta
|
|
|
|
Args:
|
|
seconds: Number of seconds to format
|
|
|
|
Returns:
|
|
Human-readable time string (e.g., "1 day 2 hours 3 minutes 4 seconds")
|
|
"""
|
|
td = timedelta(seconds=seconds)
|
|
|
|
# Extract components
|
|
days = td.days
|
|
hours, remainder = divmod(td.seconds, 3600)
|
|
minutes, seconds_remaining = divmod(remainder, 60)
|
|
|
|
# Build the human-readable string
|
|
parts = []
|
|
if days > 0:
|
|
parts.append(f"{days} day" if days == 1 else f"{days} days")
|
|
if hours > 0:
|
|
parts.append(f"{hours} hour" if hours == 1 else f"{hours} hours")
|
|
if minutes > 0:
|
|
parts.append(f"{minutes} minute" if minutes == 1 else f"{minutes} minutes")
|
|
if seconds_remaining > 0 or not parts: # Include seconds if no other parts or if seconds exist
|
|
parts.append(f"{seconds_remaining} second" if seconds_remaining == 1 else f"{seconds_remaining} seconds")
|
|
|
|
return " ".join(parts)
|
|
|
|
def calculate_time_remaining(start_time: float, duration_required: float, current_time: Optional[float] = None) -> float:
|
|
"""
|
|
Calculate remaining time for a duration requirement
|
|
|
|
Args:
|
|
start_time: When the timer started
|
|
duration_required: Total duration required
|
|
current_time: Current time (defaults to time.time())
|
|
|
|
Returns:
|
|
Remaining time in seconds (0 if elapsed time exceeds requirement)
|
|
"""
|
|
import time
|
|
current = current_time or time.time()
|
|
elapsed = current - start_time
|
|
return max(0, duration_required - elapsed) |