Skip to content

Commit

Permalink
add time format
Browse files Browse the repository at this point in the history
  • Loading branch information
supercoderhawk committed Oct 26, 2020
1 parent f7b250d commit 02a0ab9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
20 changes: 20 additions & 0 deletions pysenal/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,23 @@ def json_serialize(obj):
return str(obj)
except:
raise TypeError(repr(obj) + ' is not JSON serializable')


def format_time(seconds):
"""
format seconds to time string
:param seconds: seconds, in float format
:return: formatted time string
"""
h = int(seconds // 3600)
m = int(seconds % 3600 // 60)
s = seconds % 60

if h:
time_str = '{:d}h {:d}min {:.02f}s'.format(h, m, s)
elif m:
time_str = '{:d}min {:.02f}s'.format(m, s)
else:
time_str = '{:.02f}s'.format(s)

return time_str
9 changes: 9 additions & 0 deletions tests/utils/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,12 @@ def test_json_serialize():
assert json_serialize(Decimal('11.0')) == '11.0'
assert json_serialize(b'123') == "b'123'"
assert json_serialize(11) == '11'


def test_format_time():
assert format_time(60) == '1min 0.00s'
assert format_time(60.1) == '1min 0.10s'
assert format_time(3600) == '1h 0min 0.00s'
assert format_time(3660.1121) == '1h 1min 0.11s'

assert format_time(12.2132145) == '12.21s'

0 comments on commit 02a0ab9

Please sign in to comment.