如何将无零数字序列按日期规则排序并提取最后一项
数字序列转日期排序并获取最后一项的实现方法
核心步骤
提取纯数字部分
从类似P_xxxxxx的输入字符串中,拆分出下划线后的纯数字序列,比如从P_2024713812中提取2024713812。解析为标准日期时间格式
按照日期时间的合法规则拆分数字串,补全前导零生成YYYY-MM-DD HH:MM格式:- 固定前4位为年份(如
2024) - 后续依次拆分月份(1-2位,需≤12)、日期(1-2位,需≤31)、小时(1-2位,需≤23)、分钟(1-2位,需≤59),不足2位的补前导零
- 示例:
20241151212→2024-11-05 12:12,202411111→2024-01-01 11:01
- 固定前4位为年份(如
排序并取最后一项
将所有转换后的标准日期字符串(或对应的时间戳)进行升序排序,排序后的最后一项即为时间最晚的原始字符串。
代码示例(Python)
def parse_to_datetime_str(s): # 提取下划线后的数字串 num_str = s.split('_')[1] idx = 0 # 提取年份 year = num_str[idx:idx+4] idx += 4 # 提取月份 if idx + 1 < len(num_str) and int(num_str[idx:idx+2]) <= 12: month = num_str[idx:idx+2] idx += 2 else: month = num_str[idx].zfill(2) idx += 1 # 提取日期 if idx + 1 < len(num_str) and int(num_str[idx:idx+2]) <= 31: day = num_str[idx:idx+2] idx += 2 else: day = num_str[idx].zfill(2) idx += 1 # 提取小时 if idx + 1 < len(num_str) and int(num_str[idx:idx+2]) <= 23: hour = num_str[idx:idx+2] idx += 2 else: hour = num_str[idx].zfill(2) idx += 1 # 提取分钟,不足补零 minute = num_str[idx:].zfill(2) if idx < len(num_str) else '00' return f"{year}-{month}-{day} {hour}:{minute}" # 测试数据 items = ["P_2024713812", "P_20241151212", "P_202411111"] # 生成日期与原始项的配对列表 date_item_pairs = [(parse_to_datetime_str(item), item) for item in items] # 按日期升序排序 date_item_pairs.sort() # 获取最后一项(时间最晚的原始字符串) last_item = date_item_pairs[-1][1] print(last_item) # 输出: P_20241151212
注意事项
- 解析时必须校验各部分的合法范围(如月份不能超过12),避免错误拆分数字串
- 标准日期字符串本身可直接用于排序,无需额外转换为时间戳,简化实现
- 若存在相同日期的项,排序后可根据需求选择保留所有或任意一个
内容的提问来源于stack exchange,提问作者imiezmistral
相关产品推荐
相关产品推荐

