Skip to content

Commit 02a0ab9

Browse files
add time format
1 parent f7b250d commit 02a0ab9

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

pysenal/utils/utils.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,23 @@ def json_serialize(obj):
131131
return str(obj)
132132
except:
133133
raise TypeError(repr(obj) + ' is not JSON serializable')
134+
135+
136+
def format_time(seconds):
137+
"""
138+
format seconds to time string
139+
:param seconds: seconds, in float format
140+
:return: formatted time string
141+
"""
142+
h = int(seconds // 3600)
143+
m = int(seconds % 3600 // 60)
144+
s = seconds % 60
145+
146+
if h:
147+
time_str = '{:d}h {:d}min {:.02f}s'.format(h, m, s)
148+
elif m:
149+
time_str = '{:d}min {:.02f}s'.format(m, s)
150+
else:
151+
time_str = '{:.02f}s'.format(s)
152+
153+
return time_str

tests/utils/test_utils.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,12 @@ def test_json_serialize():
115115
assert json_serialize(Decimal('11.0')) == '11.0'
116116
assert json_serialize(b'123') == "b'123'"
117117
assert json_serialize(11) == '11'
118+
119+
120+
def test_format_time():
121+
assert format_time(60) == '1min 0.00s'
122+
assert format_time(60.1) == '1min 0.10s'
123+
assert format_time(3600) == '1h 0min 0.00s'
124+
assert format_time(3660.1121) == '1h 1min 0.11s'
125+
126+
assert format_time(12.2132145) == '12.21s'

0 commit comments

Comments
 (0)