如何修复TypeError:int与NoneType不支持减法运算的问题
问题解析与修复方案
错误原因
你遇到的TypeError: unsupported operand type(s) for -: 'int' and 'NoneType',是因为计算会话时长时仅判断了end_time不为空,但未检查start_time是否存在。当某个会话只有END记录、没有对应的START记录时,start_time仍为None,此时用整数类型的end_time减去None就会触发该错误。
修复代码
修改计算duration的条件判断,同时检查start_time和end_time是否都不为None,关键代码调整如下:
# 替换原有的duration计算行 session['duration'] = session['end_time'] - session['start_time'] if (session['end_time'] is not None and session['start_time'] is not None) else None
同时优化时间格式化输出的容错性,完整修复后的脚本如下:
import json from datetime import datetime def parse_output_file(file_path): with open(file_path, 'r') as file: data = json.load(file) sessions = {} for record in data: session_id = record['id'] session_type = record['type'] timestamp = int(record['timestamp']) comments = record.get('comments', '') if session_id not in sessions: sessions[session_id] = {'id': session_id, 'start_time': None, 'end_time': None, 'duration': None, 'late_return': False, 'damaged': False, 'comments': ''} if session_type == 'START': sessions[session_id]['start_time'] = timestamp elif session_type == 'END': sessions[session_id]['end_time'] = timestamp sessions[session_id]['damaged'] = bool(comments) sessions[session_id]['comments'] = comments for session in sessions.values(): # 避免start_time/end_time为None时格式化报错 start_time = datetime.fromtimestamp(session['start_time']).strftime('%Y-%m-%d %H:%M:%S') if session['start_time'] is not None else "未记录" end_time = datetime.fromtimestamp(session['end_time']).strftime('%Y-%m-%d %H:%M:%S') if session['end_time'] is not None else "未记录" # 同时校验开始和结束时间是否存在 session['duration'] = session['end_time'] - session['start_time'] if (session['end_time'] is not None and session['start_time'] is not None) else None late_return = session['duration'] > 24 * 3600 if session['duration'] is not None else False session['late_return'] = late_return print(f"Session ID: {session['id']}") print(f"Start Time: {start_time}") print(f"End Time: {end_time}") print(f"Duration: {session['duration']} seconds" if session['duration'] is not None else "Duration: 无效(缺少开始/结束时间)") print(f"Late Return: {late_return}") print(f"Damaged: {session['damaged']}") print(f"Comments: {session['comments']}") print() file_path = r'output.json' parse_output_file(file_path)
额外优化建议
- 处理原始数据时,可对每个会话的
START/END记录做校验,比如发现同一个会话存在多条START或END记录时,输出警告或做合并处理。 - 对缺少
start_time或end_time的会话,输出时明确标记为无效,方便排查数据问题。
内容的提问来源于stack exchange,提问作者David Oh
相关产品推荐
相关产品推荐

