pandas.datetime addition: What's wrong?

MRAB python at mrabarnett.plus.com
Tue Jun 7 23:08:59 EDT 2016


On 2016-06-08 03:09, Paulo da Silva wrote:
> Hi all!
>
> What's wrong with this?
>
> import pandas as pd
> x=pd.to_datetime("20160501")
>
> x+pd.DateOffset(days=1)
> Timestamp('2016-05-02 00:00:00', tz=None)
>
> x.__add__(pd.DateOffset(days=1))
> NotImplemented
>
>
> More generally I have a class derived from pandas.datetime and I want to
> implement its own __add__ that at a given point call super __add__.
>
> For example:
>
> class C(pandas.datetime):
> 	...
> 	def __add__(self,n):
> 		...
> 		r=super(C,self).__add__(pd.DateOffset(days=n))
> 		...
> BTW, in the last line is it needed and how to "cast" self to
> pandas.datetime?
>
> Thanks for any help
>
When you have x+y, it tries x.__add__(y). If that fails, it then tries 
y.__radd__(x).

Does that mean that the calculation above is actually implemented by the 
DateOffset class?

Does pd.to_datetime return a datetime instance?

I suspect what's happening is that it's returning NotImplemented because 
you're adding a DateOffset instance (from the pandas module) to a 
datetime instance returned by pd.to_datetime (from the datetime module), 
and the datetime class doesn't know about the DateOffset class. By 
calling the dunder method directly, you're not giving Python the 
opportunity to try the other dunder method.




More information about the Python-list mailing list