Skip to main content
 首页 » 编程设计

python之比较两个日期列并验证日期是否早于日期

2025年05月04日12yjmyzz

我有两列日期 (mm/dd/yy)。我需要验证 DateColumn_A 是否在 DateColumn_B 之前。

我使用了以下代码,但出现了错误“TypeError:必须是字符串,而不是系列”。请帮助初学者。

代码:

Column_A = datetime.strptime(df['DateColumn_A'], '%m %d %y') 
Column_B = datetime.strptime(df['DateColumn_B'], '%m %d %y') 
 
for index, row in dataframe.iterrows(): 
    if row[Column_A] < row[Column_B] 
        print (index,row[Column_A]) 
    else: 
        pass 

请您参考如下方法:

你可以这样比较它们:

from datetime import datetime 
 
Column_A = datetime.strptime(df['DateColumn_A'], '%m %d %y').date() 
Column_B = datetime.strptime(df['DateColumn_B'], '%m %d %y').date() 
diff = Column_A - Column_B 
if diff > 0: 
    # Column_A is greater than Column_B 
else: 
    # Column_B is greater than Column_A