mirror of
https://github.com/open-metadata/OpenMetadata.git
synced 2026-01-08 13:36:32 +00:00
chore: timedelta to string (#16985)
implemented utils.time_utils..timedelta_to_string
This commit is contained in:
parent
bf4d505608
commit
98d0e10783
@ -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})"
|
||||
|
||||
25
ingestion/tests/unit/metadata/utils/test_time_utils.py
Normal file
25
ingestion/tests/unit/metadata/utils/test_time_utils.py
Normal 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)
|
||||
Loading…
x
Reference in New Issue
Block a user