Pandas: increment datetime

冷暖自知 提交于 2020-02-01 04:39:06

问题


I need to do some actions with date in df column

buys['date_min'] = (buys['date'] - MonthDelta(1))
buys['date_min'] = (buys['date'] + timedelta(days=5))

But it return

TypeError: incompatible type [object] for a datetime/timedelta operation

How can I do it to column?


回答1:


I think you need first convert column date to_datetime, because type od values in column date is string:

buys['date_min'] = (pd.to_datetime(buys['date']) - MonthDelta(1))
buys['date_min'] = (pd.to_datetime(buys['date']) + timedelta(days=5))

EDIT:

You need parameter format to to_datetime and then another solution is with to_timedelta

buys = pd.DataFrame({'date':['01.01.2016','20.02.2016']})
print (buys)
         date
0  01.01.2016
1  20.02.2016

buys['date']= pd.to_datetime(buys['date'],format='%d.%m.%Y') 
buys['date_min'] = buys['date'] + pd.to_timedelta(5,unit='d')
print (buys)
        date   date_min
0 2016-01-01 2016-01-06
1 2016-02-20 2016-02-25


来源:https://stackoverflow.com/questions/38242692/pandas-increment-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!