Skip to content
Merged
Show file tree
Hide file tree
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
34 changes: 8 additions & 26 deletions src/anemoi/utils/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,39 +260,21 @@ def frequency_to_string(frequency: datetime.timedelta) -> str:
A string representation of the frequency.
"""

frequency = frequency_to_timedelta(frequency)
total_seconds = int(frequency.total_seconds())

total_seconds = frequency.total_seconds()
if total_seconds < 0:
return f"-{frequency_to_string(-frequency)}"
assert int(total_seconds) == total_seconds, total_seconds
total_seconds = int(total_seconds)

seconds = total_seconds
if total_seconds % (24 * 3600) == 0:
return f"{total_seconds // (24 * 3600)}d"

days = seconds // (24 * 3600)
seconds %= 24 * 3600
hours = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if total_seconds % 3600 == 0:
return f"{total_seconds // 3600}h"

if days > 0 and hours == 0 and minutes == 0 and seconds == 0:
return f"{days}d"
if total_seconds % 60 == 0:
return f"{total_seconds // 60}m"

if days == 0 and hours > 0 and minutes == 0 and seconds == 0:
return f"{hours}h"

if days == 0 and hours == 0 and minutes > 0 and seconds == 0:
return f"{minutes}m"

if days == 0 and hours == 0 and minutes == 0 and seconds > 0:
return f"{seconds}s"

if days > 0:
return f"{total_seconds}s"

return str(frequency)
return f"{total_seconds}s"


def frequency_to_seconds(frequency: int | str | datetime.timedelta) -> int:
Expand Down
5 changes: 3 additions & 2 deletions tests/test_frequency.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
def test_frequency_to_string() -> None:
"""Test the frequency_to_string function for converting timedelta to string."""
assert frequency_to_string(datetime.timedelta(hours=1)) == "1h"
assert frequency_to_string(datetime.timedelta(hours=1, minutes=30)) == "1:30:00"
assert frequency_to_string(datetime.timedelta(hours=1, minutes=30)) == "90m"
assert frequency_to_string(datetime.timedelta(days=10)) == "10d"
assert frequency_to_string(datetime.timedelta(hours=30)) == "30h"
assert frequency_to_string(datetime.timedelta(minutes=10)) == "10m"
assert frequency_to_string(datetime.timedelta(minutes=90)) == "1:30:00"
assert frequency_to_string(datetime.timedelta(minutes=90)) == "90m"


def test_frequency_to_timedelta() -> None:
Expand Down
Loading