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

如何在Python中按日期升序排序含日期时间的文件名?

问题解决:按日期时间排序JSON数据文件

问题现状

遍历项目./Data/目录获取文件列表后,通过切片移除.rpb文件保留JSON文件,但列表排序不符合预期——字符串排序会把h010.json排在h02.json之前,无法按年→月→日→小时的升序排列。

解决方案

1. 更可靠的JSON文件筛选

放弃依赖文件顺序的切片筛选,直接通过文件后缀判断保留.json文件,避免因目录遍历顺序变化导致的错误。

2. 提取日期时间作为排序依据

从文件路径中解析出年、月、日、小时的数值,以此作为排序key,实现自然的日期时间升序。

修改后的完整代码

import json
import csv
import sys
import os
from os import walk, path
import re
from datetime import datetime

if __name__ == "__main__":
    mypath = "./Data/"
    filenames = []
    
    # 遍历目录,仅收集.json文件
    for root, dirs, files in walk(mypath):
        for name in files:
            if name.endswith(".json") and name != "output.csv":  # 排除不需要的csv文件
                full_path = path.join(root, name)
                filenames.append(full_path)
    
    # 定义排序key的提取函数
    def get_sort_key(file_path):
        # 从路径中匹配年、月、日、小时的数字
        # 路径格式示例: ./Data/2022\8\1\h00.json
        pattern = r"./Data/(\d+)\\(\d+)\\(\d+)\\h(\d+)\.json"
        match = re.match(pattern, file_path)
        if match:
            # 转为整数,确保数值排序
            year = int(match.group(1))
            month = int(match.group(2))
            day = int(match.group(3))
            hour = int(match.group(4))
            return (year, month, day, hour)
        # 异常情况返回默认值,放在末尾
        return (9999, 12, 31, 23)
    
    # 按日期时间升序排序
    sorted_filenames = sorted(filenames, key=get_sort_key)
    
    # 打印结果
    print("按日期排序后的JSON文件列表:")
    for f in sorted_filenames:
        print(f)

代码说明

  • 筛选逻辑:直接判断文件后缀为.json,同时排除output.csv(如果存在),比切片更稳定。
  • 排序key:通过正则表达式提取路径中的年、月、日、小时,转为整数元组后排序,元组会按元素顺序依次比较,完美实现日期时间升序。
  • 兼容性:不管目录遍历顺序如何,最终排序结果都符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 04:36:22