You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中按StartTs排序对象列表并获取最新时间对象

Python按StartTs字段排序并获取最新对象

输入数据

data = [
    {"StartTs": "2023-02-12 15:49:38"},
    {"StartTs": "2023-02-08 19:02:00"},
    {"StartTs": "2023-02-22 17:02:00"}
]

方法一:排序后获取最新对象

由于StartTs的格式是YYYY-MM-DD HH:MM:SS,字符串的字典序与时间顺序完全一致,因此可以直接基于字符串排序:

# 按时间降序排序,取第一个元素即为最新对象
sorted_data = sorted(data, key=lambda x: x["StartTs"], reverse=True)
latest_obj = sorted_data[0]
print(latest_obj)  # 输出: {'StartTs': '2023-02-22 17:02:00'}

方法二:用max函数直接获取(更高效)

不需要对整个列表排序,通过max函数一次遍历即可得到结果,时间复杂度更低:

# 以StartTs为比较键,直接获取时间最新的对象
latest_obj = max(data, key=lambda x: x["StartTs"])
print(latest_obj)  # 输出: {'StartTs': '2023-02-22 17:02:00'}

内容的提问来源于stack exchange,提问作者Spoorthi Devang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:30:11