【问题标题】:Cannot compare dates between date variable and pandas dataframe无法比较日期变量和熊猫数据框之间的日期
【发布时间】:2021-03-21 16:42:36
【问题描述】:

在将可变日期与 pandas 日期数据集进行比较时,我遇到了一个令人沮丧的问题。无论我尝试什么格式选项,我都无法让它们保持一致。 请大家帮忙,我基本上只需要比较pandas数据集中的日期和今天的日期+ 6个月。

我的代码:

SourceData_Workbook = R"G:\AR\REPORTS\Automation Files\Credit Risk\test1.xlsx"

SourceInPandas = pd.read_excel(SourceData_Workbook, skiprows=33,header=0,index=False)

# Creating date variable + 6 months
six_months = date.today() + relativedelta(months=+6)


# Formatting sourced data to date format
SourceInPandas['Req.dlv.dt']=SourceInPandas['Req.dlv.dt'].apply(lambda x:datetime.strptime(x,'%d.%m.%Y'))

# Fails on this line
SourceInPandas.loc[(SourceInPandas['Req.dlv.dt']<= six_months) & (SourceInPandas['OpIt'] != "15 Overdue account")& (SourceInPandas['OpIt'] != "16 Prepayment required")& (SourceInPandas['OpIt'] != "17 Approval required"),"OpIt"]="Future delivery" 

堆栈跟踪:

TypeError: Invalid comparison between dtype=datetime64[ns] and date 

【问题讨论】:

    标签: python excel pandas date formatting


    【解决方案1】:

    您可以将TimestampTimestamp.floor 一起使用,并由DateOffset 添加6 个月:

    six_months = pd.Timestamp('today').floor('d') + pd.DateOffset(months=6)
    print (six_months)
    2021-06-10 00:00:00
    
    SourceInPandas['Req.dlv.dt']=pd.to_datetime(SourceInPandas['Req.dlv.dt'], dayfirst=True)
    

    【讨论】:

    • 不幸的是,即使这样也会打印相同的错误:dtype=datetime64[ns] and date 之间的比较无效
    • Diky uz 到 hrne! Zdravim SK z 布尔纳。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    相关资源
    最近更新 更多