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

Python处理资产时间数据:计算间隔、夜间时长及差值需求

解决方案

首先确认你的local_time列已转为datetime类型,未转换的话先执行:

import pandas as pd
import numpy as np

df['local_time'] = pd.to_datetime(df['local_time'])

注意你第一步代码里的groupby('assetline')是笔误,对应列名应为asset,修正后:

df['duration_min'] = round((df.groupby('asset')['local_time'].shift(-1).sub(df['local_time']).dt.total_seconds()/60).abs(), 1)

第二步:计算时间间隔中的夜间(21:00-次日6:00)时长

编写自定义函数处理单个时间区间的夜间时长统计,再批量应用到数据中:

def calculate_night_duration(start, end):
    # 处理无后续时间点的行(最后一行)
    if pd.isna(end):
        return np.nan
    
    # 定义当天夜间开始时间和次日夜间结束时间
    night_start = start.replace(hour=21, minute=0, second=0)
    next_day_night_end = start.replace(hour=6, minute=0, second=0) + pd.Timedelta(days=1)
    full_night_min = 540  # 21:00到次日6:00共9小时=540分钟

    # 分场景计算夜间时长
    if start >= night_start and end <= next_day_night_end:
        # 整个区间都在夜间
        return round((end - start).total_seconds()/60, 1)
    elif end <= night_start or start >= next_day_night_end:
        # 整个区间都在白天
        return 0.0
    elif start < night_start and end <= next_day_night_end:
        # 区间跨夜间开始(白天到夜间)
        return round((end - night_start).total_seconds()/60, 1)
    elif start >= night_start and end > next_day_night_end:
        # 区间跨夜间结束(夜间到白天)
        return round((next_day_night_end - start).total_seconds()/60, 1)
    elif start < night_start and end > next_day_night_end:
        # 区间覆盖完整夜间
        return full_night_min

# 先存储每个时间点的下一个时间(按asset分组)
df['next_local_time'] = df.groupby('asset')['local_time'].shift(-1)
# 应用函数计算夜间时长
df['night_duration_min'] = df.apply(lambda row: calculate_night_duration(row['local_time'], row['next_local_time']), axis=1)

第三步:计算总时长与夜间时长的差值

df['day_duration_min'] = df['duration_min'] - df['night_duration_min']

测试结果

针对你提供的测试数据:

local_time           asset
2022-10-04 07:14:31  12345
2022-10-04 07:14:22  12345
2022-10-01 18:43:19  67899

执行后会得到:

  • 前两行属于asset 12345,时间间隔0.2分钟(均在白天),所以night_duration_min为0,day_duration_min为0.2
  • 第三行无后续时间点,相关计算列均为NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:32:34