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

如何实现忽略指定非计数日期的日期差值计算函数?

Calculate Time Difference Excluding Specific Marked Days

Got it, let's tackle this problem where we need to compute the time difference between two datetime points but exclude full days marked with key=1 (since the standard weekend-only exclusion doesn't apply here). Here's a practical, tested solution that matches your example requirements perfectly:

Core Approach

The key idea is to break the problem down into simple steps:

  1. Calculate the raw total time difference between the two datetimes.
  2. Identify all full days that fall strictly between the start and end dates.
  3. Subtract the total seconds of any days marked as non-countable (key=1) from the raw difference.

Full Code Implementation

First, let's make sure our date data is properly formatted for easy matching, then build the function:

import pandas as pd
from datetime import datetime, timedelta

# Example data setup
data = {'Date':['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04'], 'key':[0, 0, 1, 0]}
df = pd.DataFrame(data)
# Convert Date column to datetime type for seamless comparison
df['Date'] = pd.to_datetime(df['Date'])

def subtract_function(date2, date1):
    # Calculate raw total seconds between the two input times
    total_raw_seconds = (date2 - date1).total_seconds()
    
    # Extract just the date components (no time) from start and end datetimes
    start_date_only = date1.date()
    end_date_only = date2.date()
    
    # Edge case: start and end are on the same day, no full days to exclude
    if start_date_only == end_date_only:
        return total_raw_seconds
    
    # Generate all full days that lie between start and end (exclusive of both)
    middle_full_days = pd.date_range(
        start=start_date_only + timedelta(days=1),
        end=end_date_only - timedelta(days=1),
        freq='D'
    )
    
    # Count how many of these middle days are marked as non-countable (key=1)
    excluded_day_count = df[df['Date'].isin(middle_full_days) & (df['key'] == 1)].shape[0]
    
    # Convert excluded days to total seconds and subtract from raw difference
    excluded_seconds = excluded_day_count * 86400  # 86400 seconds = 1 full day
    effective_seconds = total_raw_seconds - excluded_seconds
    
    return effective_seconds

# Test with your example dates
date1 = datetime.strptime('2019-01-02 21:00:00', '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime('2019-01-04 17:00:00', '%Y-%m-%d %H:%M:%S')

print(subtract_function(date2, date1))  # Output: 72000.0

How This Works

  • Date Formatting: We convert the Date column in the DataFrame to datetime objects so we can easily match them against the date parts of our input datetimes.
  • Raw Difference: We start with the full unadjusted time difference in seconds as a baseline.
  • Middle Days Filter: We generate all full days that lie strictly between the start and end dates (since partial days at the start/end are always counted—only full days can be excluded).
  • Exclusion Calculation: We count how many of those middle days are marked key=1, convert that count to total seconds, and subtract it from the raw difference to get the final effective time.

Performance Optimization (For Large Datasets)

If you're working with a large date range or a big DataFrame, prepping a date-to-key mapping will speed up lookups significantly:

# Preprocess once: create a Series with dates as index for fast lookups
date_key_mapping = df.set_index('Date')['key']

# Then in the function, replace the excluded_day_count line with:
excluded_day_count = date_key_mapping.loc[middle_full_days].sum()

This avoids the slower isin() check and is much more efficient for large-scale data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 09:02:28