assuming the following code:
from datetime import datetime
start_time = datetime.now()
end_time = datetime.now()
delta = end_time - start_time
delta_ms = delta.microseconds
what is the most elegant way to simplify the conversion of the timedelta object to mins,secs and millisecs?
The one-liner I have below, requires two calculations of divmod(delta_ms,1000)
, is there any way, keeping it to one line, that it only needs to be calculated once?
mins,secs,ms = divmod(divmod(delta_ms,1000),60) + (divmod(delta_ms,1000)[1],)
I also have the following, which is two lines of code but only calculates divmod(delta_ms,1000)
once:
unwrap = lambda x: divmod(x[0],60) + (x[1],)
mins,secs,ms = unwrap(divmod(delta_ms,1000))
First of all, you missed a [0]
in your second divmod
:) You might want to change that:
mins,secs,ms = divmod(divmod(delta_ms,1000)[0],60) + (divmod(delta_ms,1000)[1],)
Answering your question, if you are looking for elegant based on amount of lines it takes up, than your above solution would the most so. However, you are running divmod
an extra, unnecessary time, which can be solved in one-line (much less elegant, uses ;
):
var1, var2 = divmod(delta_ms,1000);mins,secs,ms = divmod(var1,60) + (var2,)
Or two lines:
var1, var2 = divmod(delta_ms,1000)
mins,secs,ms = divmod(var1,60) + (var2,)