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

如何在Python DataFrame中判断date1列日期是否处于date2列日期的±10天范围内

Check if date1 is within ±10 days of date2 in a Pandas DataFrame

Got it, let's walk through how to solve this problem step by step. The core goal is to verify if each date in the date1 column falls within a 10-day window (either before or after) the corresponding date in the date2 column.

Step 1: Convert date columns to datetime type

First up, we need to turn those string dates into proper datetime objects—strings can't be used to calculate date differences reliably. We'll use pd.to_datetime() and explicitly set the format parameter since our dates follow the DD/MM/YYYY pattern.

Step 2: Calculate date differences and check the 10-day condition

Once we have datetime-formatted columns, we can compute the absolute difference between date1 and date2, extract the number of days from that difference, and check if it's 10 or less.

Full code example

import pandas as pd

# Create the sample DataFrame from your scenario
df = pd.DataFrame({
    'date1': ['13/08/2021'],
    'date2': ['21/08/2021']
})

# Convert string dates to datetime objects
df['date1'] = pd.to_datetime(df['date1'], format='%d/%m/%Y')
df['date2'] = pd.to_datetime(df['date2'], format='%d/%m/%Y')

# Add a new column with the boolean check result
df['within_10_days'] = abs(df['date1'] - df['date2']).dt.days <= 10

# Print the result
print(df['within_10_days'])

Why the sample returns True

In your example, the difference between 13/08/2021 and 21/08/2021 is 8 days—this is well within the ±10 day range, so the output will be a Series with the value True.

This logic works for multiple rows too: it will check each pair of dates individually and return a boolean value for every entry in your DataFrame.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:32:49