Get highest duration from a list of strings
Here's an absolute hack which solves the problem in a bad but clever way: Python's min
and max
functions can be used with a key
function which is used to compare elements, so that it returns the element minimising or maximising that function. If the key
function returns a tuple, then the order is determined by the first component of the tuple, using the second component as a tie-breaker.
We can exploit the fact that the last characters 'd'
, 'h'
and 'm'
can be compared in alphabetical order; a day is longer than an hour is longer than a minute. This means the longest duration has the minimum character in alphabetical order, with the maximum integer as a tie-breaker. Maximising that integer is the same as minimising its negation:
>>> durations = ['5d', '20h', '1h', '7m', '14d', '1m']
>>> min(durations, key=lambda d: (d[-1], -int(d[:-1])))
'14d'
Pure python solution. We could store mapping between our time extensions (m
, h
, d
) and minutes (here time_map
), to find highest duration. Here we're using max()
with key
argument to apply our mapping.
inp = ['5d', '20h', '1h', '7m', '14d', '1m']
time_map = {'m': 1, 'h': 60, 'd': 24*60}
print(max(inp, key=lambda x:int(x[:-1])*time_map[x[-1]])) # -> 14d
np.argmax
on pd.to_timedelta
:
import numpy as np
import pandas as pd
durations = ['5d', '20h', '1h', '7m', '14d', '1m']
durations[np.argmax(pd.to_timedelta(durations))]
Out[24]: '14d'
pd.to_timedelta
turns a string into a duration (source), and np.argmax
returns the index of the highest element.