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

Oracle中如何计算两个带时间日期的间隔分钟数(排除周末)

计算带时间日期间隔分钟数(排除周末)

核心思路是先算出两个时间点的总间隔分钟数,再减去这段时间内所有属于周末(周六、周日)的分钟数,分两种情况处理:完整的周末日和部分覆盖的周末时段。

实现步骤

  1. 计算两个日期时间的总间隔分钟数
  2. 遍历时间范围内的每一天,判断是否为周末:
    • 如果是完整的周末日(当天00:00到次日00:00都在时间范围内),则减去1440分钟(24*60)
    • 如果是部分覆盖的周末时段(仅当天部分时间在范围内),则减去实际覆盖的分钟数
  3. 最终结果 = 总间隔分钟数 - 周末总分钟数

Python示例代码

from datetime import datetime, timedelta

def get_minutes_exclude_weekend(start_time: str, end_time: str, date_format="%Y-%m-%d %H:%M:%S") -> float:
    start = datetime.strptime(start_time, date_format)
    end = datetime.strptime(end_time, date_format)
    
    total_min = (end - start).total_seconds() / 60
    if total_min < 0:
        return 0.0
    
    weekend_total = 0.0
    current_day = start
    
    while current_day < end:
        next_day = current_day + timedelta(days=1)
        # 判断是否为周六(5)或周日(6)
        if current_day.weekday() in (5, 6):
            if next_day <= end:
                # 完整的周末日,加全天分钟数
                weekend_total += 1440
            else:
                # 仅覆盖周末的一部分时间
                weekend_total += (end - current_day).total_seconds() / 60
        current_day = next_day
    
    return round(total_min - weekend_total, 2)

# 测试示例
# 示例1:不跨周末
print(get_minutes_exclude_weekend("2024-05-20 09:30:00", "2024-05-24 17:45:00"))
# 示例2:跨周末(周五下午到周一上午)
print(get_minutes_exclude_weekend("2024-05-24 16:00:00", "2024-05-27 09:00:00"))

说明

  • 代码中weekday()方法返回值:0=周一,6=周日,因此判断5、6为周末
  • 可通过修改date_format参数适配不同的日期时间格式
  • 处理了结束时间早于开始时间的边界情况,返回0
  • 最终结果保留两位小数,可根据需求调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 07:35:08