Python 删除日期忽略特定日期

Python 删除日期忽略特定日期,python,pandas,datetime,Python,Pandas,Datetime,我想减去日期,忽略特定的日子,不仅仅是周末,还有其他一些日子,所以在这种情况下不起作用 给定一个引用一天是否应该计数的表,我如何实现忽略这些天的减法函数 数据={'Date':['2019-01-01','2019-01-02','2019-01-03','2019-01-04','key':[0,0,1,0]} df=pd.DataFramedata 如果key==1,则在类似问题中,这一天不应算作周末 从日期时间导入日期时间 date1=datetime.strTime'2019-01-02

我想减去日期,忽略特定的日子,不仅仅是周末,还有其他一些日子,所以在这种情况下不起作用

给定一个引用一天是否应该计数的表,我如何实现忽略这些天的减法函数

数据={'Date':['2019-01-01','2019-01-02','2019-01-03','2019-01-04','key':[0,0,1,0]} df=pd.DataFramedata 如果key==1,则在类似问题中,这一天不应算作周末

从日期时间导入日期时间 date1=datetime.strTime'2019-01-02 21:00:00',“%Y-%m-%d%H:%m:%S” date2=datetime.strTime'2019-01-04 17:00:00',“%Y-%m-%d%H:%m:%S” 日期2-1 出[50]: datetime.timedeltadays=1,秒=72000 预期产出:
减法函数Date2,date1应该返回72000秒

我希望这就是您想要的

import pandas as pd
from datetime import datetime, timedelta

df = pd.DataFrame({
    'Date':['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04'],
    'key':[0, 0, 1, 0]
    })

# transform df Dates to datetime type
df['Date'] = pd.to_datetime(df['Date']) 

# create list of the dates to be excluded
excl_dates_list = df.query('key==1').Date.to_list() 

# input dates to count the range
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')

# the substraction function:
def substract_function(date2,date1):
    # if the first day is to be excluded, change it to the next day and start from 00:00 (so that 0 seconds are captured for this first day)
    if date1.date() in excl_dates_list:
        date1 = date1.replace(hour=0, minute=0, second=0) + timedelta(days=1)

    # if the last day is to be excluded, change it so it starts from 00:00 (so that 0 seconds are captured for this last day)
    if date2.date() in excl_dates_list:
        date2 = date2.replace(hour=0, minute=0, second=0)

    # count how many whole days between start and end should be excluded
    whole_days_to_exclude = len([x for x in excl_dates_list if (x>date1.date()) & (x<date2.date())])

    # return the substraction minus the number of days to be excluded
    return (date2-date1) - timedelta(days=whole_days_to_exclude)

substract_function(date2,date1)

我会选择一个函数来减去两个日期,然后进一步减去你想要排除的日期数[DATE1,DATE2]。朱利安,如果我的解决方案对你有用的话,请考虑投票。