chore: timedelta to string (#16985)

implemented utils.time_utils..timedelta_to_string
This commit is contained in:
Imri Paran 2024-07-11 14:23:07 +02:00 committed by GitHub
parent bf4d505608
commit 98d0e10783
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 65 additions and 0 deletions

View File

@ -14,6 +14,7 @@ Time utility functions
"""
from datetime import datetime, time, timedelta, timezone
from math import floor
from typing import Union
from metadata.utils.helpers import datetime_to_ts
@ -124,3 +125,42 @@ def convert_timestamp_to_milliseconds(timestamp: Union[int, float]) -> int:
if len(str(round(timestamp))) == 13:
return timestamp
return round(timestamp * 1000)
def timedelta_to_string(td: timedelta):
"""Convert timedelta to human readable string
Example:
>>> timedelta_to_string(timedelta(days=1, hours=2, minutes=3, seconds=4))
'1 days 2 hours 3 minutes 4 seconds (total seconds: 93784.0)'
Args:
td (timedelta): timedelta object
Returns:
str: human readable string
"""
res = []
current = td
if current.days:
res.append(f"{floor(td.days)} day")
if current.days > 1:
res[-1] += "s"
current -= timedelta(days=floor(td.days))
hours = current.seconds // 3600
if hours:
res.append(f"{hours} hour")
if hours > 1:
res[-1] += "s"
current -= timedelta(hours=hours)
minutes = current.seconds // 60
if minutes:
res.append(f"{minutes} minute")
if minutes > 1:
res[-1] += "s"
current -= timedelta(minutes=minutes)
res.append(f"{current.seconds} second")
if current.seconds != 1:
res[-1] += "s"
total_seconds = "total seconds: " + str(td.total_seconds())
return " ".join(res) + f" ({total_seconds})"

View File

@ -0,0 +1,25 @@
from datetime import timedelta
import pytest
from metadata.utils.time_utils import timedelta_to_string
@pytest.mark.parametrize(
"parameter,expected",
[
(
timedelta(days=1, hours=1, minutes=1, seconds=1),
"1 day 1 hour 1 minute 1 second",
),
(timedelta(days=1), "1 day"),
(
timedelta(seconds=0),
"0 seconds",
),
(timedelta(days=1), "1 day"),
(timedelta(hours=1000000.123456), "41666 days 16 hours 7 minutes 24 seconds"),
],
)
def test_timedelta_to_string(parameter, expected):
assert timedelta_to_string(parameter).startswith(expected)