如何使用Python打印指定月份范围内的交易日志
Python按指定月份范围筛选交易日志实现方案
需求描述
需要从trans.txt交易日志中按月份范围筛选日志,支持季度/半年度统计,当前本地时间为11月时,可筛选9-11月的季度日志。
日志文件
trans.txt示例内容:22 July 2021 09:35:54 Withdrawn: RM500 22 July 2021 09:35:54 Withdrawn: RM500 22 August 2021 09:35:54 Withdrawn: RM500 22 August 2021 09:35:54 Withdrawn: RM500 22 September 2021 09:35:54 Withdrawn: RM500 22 September 2021 09:35:54 Withdrawn: RM500 22 September 2021 09:35:54 Withdrawn: RM500 22 October 2021 09:35:54 Withdrawn: RM500 22 October 2021 09:35:54 Withdrawn: RM500 22 November 2021 09:35:54 Withdrawn: RM500 22 November 2021 09:35:54 Withdrawn: RM500 22 December 2021 09:35:54 Withdrawn: RM500 22 December 2021 09:35:54 Withdrawn: RM500
原有代码问题分析
- 仅匹配当前本地月份的第一条日志就倒序截取全部内容,未做月份范围筛选逻辑
- 硬编码截取前3行,未考虑每个月日志数量不固定的场景
- 未兼容跨年月份筛选场景,也未把月份映射为数字做范围判断
修改后可运行代码
import time # 月份英文名称到数字的映射,用于范围判断 month_map = { "January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June":6, "July":7, "August":8, "September":9, "October":10, "November":11, "December":12 } # 获取本地当前月份数字 current_month = int(time.strftime("%m")) # 配置筛选月份数量,设置3为季度,设置6即为半年度 filter_month_count = 3 min_month = current_month - filter_month_count + 1 # 读取交易日志 with open("trans.txt", "r", encoding="utf-8") as f: log_lines = f.read().splitlines() # 筛选符合月份范围的日志 matched_logs = [] for line in log_lines: if not line.strip(): continue log_month_str = line.split()[1] log_month = month_map.get(log_month_str, 0) # 兼容跨年场景判断 if min_month > 0: if min_month <= log_month <= current_month: matched_logs.append(line) else: # 跨年时自动处理12月等上年月份匹配 if log_month >= (min_month + 12) or log_month <= current_month: matched_logs.append(line) # 输出到终端同时写入临时文件 with open("tempLogs.txt", "w", encoding="utf-8") as f: for log in matched_logs: print(log) f.write(log + "\n")
功能说明
- 可通过修改
filter_month_count参数灵活调整筛选范围 - 自动兼容跨年月份筛选场景,比如当前月为2月时,可自动筛选12、1、2月的日志
- 自动适配每个月的日志数量,不会漏匹配同月份的多条日志
- 筛选结果同时输出到终端和
tempLogs.txt文件
内容的提问来源于stack exchange,提问作者Darren LK
相关产品推荐
相关产品推荐

