pandas -Python-如何减去两个不同的日期列 [英] Pandas - Python - how to subtract two different date columns

查看:152
本文介绍了 pandas -Python-如何减去两个不同的日期列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图用今天的日期减去created_date列填充一列,但出现以下错误:TypeError:-:'str'和'str'的不受支持的操作数类型

Trying to have a column be filled with today's date minus the created_date column, but getting the following error : TypeError: unsupported operand type(s) for -: 'str' and 'str'

import datetime
now = datetime.date.today()
today = '{0:%m/%d/%Y}'.format(now).format(now)
today
data['Aging'] = today
data['Aging'] = data['Aging'].sub(data['Created_Date'], axis=0)

TypeError:-:"str"和"str"的不受支持的操作数类型

TypeError: unsupported operand type(s) for -: 'str' and 'str'

推荐答案

我认为需要减去datetime s,因此有必要在nowCreated_Date列中转换date,最后进行转换timedelta数天之内使用 dt.days :

I think need subtract datetimes, so is necessary convert date in now and in Created_Date column, last for convert timedeltas to days use dt.days:

import datetime
now = datetime.date.today()
today = pd.Timestamp(now)

data['Created_Date'] = pd.to_datetime(data['Created_Date'])
data['Aging'] = today
data['Aging'] = data['Aging'].sub(data['Created_Date'], axis=0).dt.days

解决方案应该简化:

data['Created_Date'] = pd.to_datetime(data['Created_Date'])
data['Aging'] = data['Created_Date'].rsub(today, axis=0).dt.days

这篇关于 pandas -Python-如何减去两个不同的日期列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆