diff --git a/ingestion/src/metadata/utils/time_utils.py b/ingestion/src/metadata/utils/time_utils.py index 1d816ef6442..ddcee67e650 100644 --- a/ingestion/src/metadata/utils/time_utils.py +++ b/ingestion/src/metadata/utils/time_utils.py @@ -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})" diff --git a/ingestion/tests/unit/metadata/utils/test_time_utils.py b/ingestion/tests/unit/metadata/utils/test_time_utils.py new file mode 100644 index 00000000000..13ef5c9d9c0 --- /dev/null +++ b/ingestion/tests/unit/metadata/utils/test_time_utils.py @@ -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)