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
Pandas: increment datetime
提问by ldevyataykina
I need to do some actions with date
in 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 date
to_datetime
, because type
od values in column date
is string
:
我认为您需要先转换 column date
to_datetime
,因为column 中的type
od 值date
是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
您需要参数format
toto_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