简体   繁体   中英

Pandas - Python - how to subtract two different date columns

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: unsupported operand type(s) for -: 'str' and 'str'

I think need subtract datetime s, so is necessary convert date in now and in Created_Date column, last for convert timedelta s 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

Solution should be simplify:

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

Maybe, try this as the full code:

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

What you want, maybe:

data['Created_Date'] = pd.to_datetime(data['Created_Date'])
data['Aging'] = pd.to_datetime('now').strftime('%m/%d/%Y')
data['Aging'] = data['Aging'].sub(data['Created_Date'], axis=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM