如何从 "hh:mm" 时间戳列表中获取最大值?

How to get the maximum out of a list of "hh:mm" timestamps?

我有一个时间字符串列表(音乐曲目长度),就像这样:

music_lengths = ['4:30', '4:59', '7:30', ...]

如何找到该列表的最大值(最长轨道)?

x = [int(element.replace(':','')) for element in music_lengths]
max(x)

你可以像这样简单地使用 sorted()(仅几分钟):

>>> music_lengths = ['4:30', '4:59', '7:30', '0:01']
>>> sorted(music_lengths, key=lambda item: int(item.split(':')[0]))
['0:01', '4:30', '4:59', '7:30']

对于更精确的分钟和秒方法 time 模块应该像 中那样使用或手动计算到秒:

>>> sorted(music_lengths, key=lambda item: int(item.split(':')[0]) * 60 + int(item.split(':')[1]))
['0:01', '4:30', '4:59', '7:30']

您可以使用 time.strptime 转换为 time 个对象,并根据这些值取最大值:

import time

music_lengths = ['4:30', '11:04', '4:59', '7:30', '1:23']
longest = max(music_lengths, key=lambda t:time.strptime(t, '%M:%S'))
print(longest)

输出(我的示例数据)

11:04

或者您可以尝试使用 pandas 如下:

import pandas as pd
if __name__ == '__main__':
    music_lengths = ["4:30", "4:59", "7:30", "3:25"]
    df = pd.DataFrame(music_lengths, columns=["length"])
    df["length"]= pd.to_datetime(df["length"], format="%H:%M").dt.time
    print(df.max())

代码将字符串列转换为日期时间列,只输出时间部分。我使用格式“%H:%M”,因为问题指出格式为“hh:mm”。

结果:

07:30:00

这可能有点长,但只是为了多样性:

>>> music_lengths = ['4:30', '4:59', '7:30', '11:40', '0:30', '22:45', 
'7:31', '12:40']
>>> 
 >>> sorted(music_lengths, key=lambda x: list(map(int, x.split(':'))))[-1]
'22:45'