Python使用pandas DataFrame拆分跨天运行设备每日时长方法咨询
跨天设备运行时长拆分解决方案
原有代码问题
- 使用
datetime.now()获取的是代码运行时的当前日期,和设备实际运行的起止日期无关联,无法匹配不同设备的跨天场景 - pandas Series不支持直接用普通
if做逐行判断,且判断逻辑写反:只有起始日期≠结束日期的跨天记录才需要拆分时长,同天运行的记录直接计算总时长即可 - 语法错误:
dt.['Start_Date']多写了点符号,正确写法是dt['Start_Date']
完整实现代码
依赖导入
import pandas as pd from datetime import datetime, timedelta
核心处理逻辑
# 1. 首先确保时间列是datetime格式,已转换可跳过 dt['Start_Time'] = pd.to_datetime(dt['Start_Time']) dt['Finish_Time'] = pd.to_datetime(dt['Finish_Time']) # 2. 定义逐行拆分时长的函数,支持跨多自然天场景 def split_daily_runtime(row): start_time = row['Start_Time'] end_time = row['Finish_Time'] current_date = start_time.date() end_date = end_time.date() split_res = [] while current_date <= end_date: # 当日0点和23:59:59边界 day_start = datetime.combine(current_date, datetime.min.time()) day_end = datetime.combine(current_date, datetime.max.time()) # 计算当日实际运行起止 actual_start = max(start_time, day_start) actual_end = min(end_time, day_end) # 计算当日运行时长,按需转换为小时/分钟 runtime_hour = round((actual_end - actual_start).total_seconds() / 3600, 2) split_res.append({ "统计日期": current_date.strftime("%d/%m/%Y"), "当日运行时长(小时)": runtime_hour }) current_date += timedelta(days=1) return split_res # 3. 应用函数并展开拆分结果 dt['拆分结果'] = dt.apply(split_daily_runtime, axis=1) result = dt.explode('拆分结果').reset_index(drop=True) result[['统计日期', '当日运行时长(小时)']] = pd.json_normalize(result['拆分结果']) result = result.drop(columns=['拆分结果'])
测试验证
用你给出的设备A示例测试:
test_df = pd.DataFrame([{ "设备名称": "设备A", "Start_Time": "2024-08-12 21:00:00", "Finish_Time": "2024-08-13 05:00:00" }]) # 运行上述处理逻辑后,会得到两条记录: # 统计日期12/08/2024对应运行时长3小时,13/08/2024对应运行时长5小时,符合预期
内容的提问来源于stack exchange,提问作者Rynx Yee
相关产品推荐
相关产品推荐

