Python计算两列不同格式日期的绝对天数差问题
Let’s walk through a straightforward, readable solution that addresses all your requirements, with a few optimizations over your initial approach:
Step 1: Standardize Date String Lengths
Your date strings are either 7 (dmmyyyy) or 8 (ddmmyyyy) characters long. We can use str.zfill(8) to quickly pad shorter strings with leading zeros—this is simpler than the lambda function you initially considered:
# Pad A and B to 8 characters (adds leading zeros to 7-digit entries) df['A'] = df['A'].str.zfill(8) df['B'] = df['B'].str.zfill(8)
Empty strings in B will become 00000000, which will later parse to NaT (Not a Time) for easy replacement.
Step 2: Convert to Datetime & Fill Missing Values
Use pd.to_datetime with the %d%m%Y format (day-month-year) to parse the standardized strings. For column B, replace any NaT values (from empty cells or invalid dates) with today’s date (normalized to remove the time component for accurate day counts):
import pandas as pd # Convert column A to datetime df['A_date'] = pd.to_datetime(df['A'], format='%d%m%Y') # Convert column B, filling missing values with today's date today = pd.Timestamp.today().normalize() df['B_date'] = pd.to_datetime(df['B'], format='%d%m%Y').fillna(today)
Step 3: Calculate Absolute Day Difference
Subtract the datetime columns, extract the days component, and take the absolute value to get your desired column C:
df['C'] = (df['A_date'] - df['B_date']).dt.days.abs()
Concise One-Liner (If You Prefer Fewer Lines)
You can combine all steps into a single statement without intermediate columns, while keeping it readable:
df['C'] = ( pd.to_datetime(df['A'].str.zfill(8), format='%d%m%Y') - pd.to_datetime(df['B'].str.zfill(8), format='%d%m%Y').fillna(pd.Timestamp.today().normalize()) ).dt.days.abs()
Key Optimizations Over Your Initial Approach
str.zfill(8)is a cleaner, more efficient way to pad leading zeros than a lambda function.- Parsing first then filling
NaTwith today’s date handles both empty Excel cells (NaN) and invalid padded strings (00000000) in one step. - Normalizing today’s date removes the time component, ensuring accurate day-to-day comparisons.
内容的提问来源于stack exchange,提问作者ggg_datascience

