pandas 熊猫:增加日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38242692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:32:09  来源:igfitidea点击:

Pandas: increment datetime

pythondatetimepandasdataframetimedelta

提问by ldevyataykina

I need to do some actions with datein df column

我需要date在 df 列中执行一些操作

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?

我怎样才能做到这一点?

回答by jezrael

I think you need first convert column dateto_datetime, because typeod values in column dateis string:

我认为您需要先转换 column dateto_datetime,因为column 中的typeod 值datestring

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 formatto to_datetimeand then another solution is with to_timedelta

您需要参数formattoto_datetime然后另一个解决方案是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