TypeError: unsupported type for timedelta days component: numpy.int32

I got the following error when i=0 in the below loop. I don’t know why? If I test the code in a separate program and it is fine. why? Thanks for your help

Code that doesn’t work:

for i in np.arange(0,delta.days+1,0.5):   
    print('day=',i)
    print(tick_min)
    nextdate = tick_min + timedelta(days=i)

Output:

day= 0
2021-01-30 17:20:38
TypeError: unsupported type for timedelta days component: numpy.int32

As a separate program, it is working:

import datetime

tick_min=datetime.datetime(2021, 1, 30, 17, 20, 38)

nextdate = tick_min + timedelta(days=0)
print(nextdate)

Output:

2021-01-30 17:20:38

Answer

As @John Gordon pointed out casting to an integer should solve this TypeError. However, newer versions of the DateTime library support both int and float values for the days component of the timedelta method. Here is the relevant passage from DateTime’s documentation datetime.timedelta.

Judging by the first code snippet, the one that contains the loop over the np.arange vector, it seems that you expect the days argument in timedelta to be a primitive of type float. Thus, casting days to an integer may lead to wrong results.

The actual issue here seems to be that the numpy vector defaults to a dtype="np.int32", due to the arguments that you pass and most probably to the version of numpy that you have installed on your system. You could address this issue by either casting to a float or substituting np.arange(0, delta.days + 1, 0.5) for np.arange(0, delta.days + 1, 0.5, dtype='float') in your loop, as using either than np.int64,np.int,np.float64, np.float will trigger a TypeError.

EDIT

@Reti43 suggested the following bug tracker issue resource identifying the reason other numpy.dtype (np.int8, np.int16, np.int32, np.float16, np.float32 etc) objects lead to a TypeError as the lack of inheritance of these objects from the primitive type objects int and float, respectively.

Leave a Reply

Your email address will not be published. Required fields are marked *