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

Python计算两列不同格式日期的绝对天数差问题

Solution to Calculate Absolute Date Difference in Pandas

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 NaT with 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:49:37