1

I have a numpy.ndarray thats values are pandas._libs.tslib.Timestamp

Example:

In: type(closedDate)

Out: numpy.ndarray

In: type(closedDate[0])

Out: pandas._libs.tslib.Timestamp

I would like to convert the contents of closedDate into a list of datetime.date

I have tried the following:

for i in closedDate:
    closedDate[i].to_datetime()

But get this error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

What to do? :/

5
  • closedDate is a numpy array not a pandas df so closedDate.values would raise an error @Ami Tavory also the existing question of this deals with pandas df at first, whereas mine is a numpy array, so it is not a duplicate :P Commented May 17, 2018 at 19:32
  • pd.to_datetime(closedDate, unit='s') Commented May 17, 2018 at 19:47
  • ValueError: non convertible value 2017-09-25 14:39:00with the unit 's' i get this error @Ami Tavory Commented May 17, 2018 at 20:04
  • It would help if you'd post a sample of the input in the question. Commented May 17, 2018 at 20:09
  • Just to address your error message (which doesn't have anything to do with your type casting): you mixed iterating over indices and iterating over elements. Either for cd in closedDate: cd.to_datetime() or for i in range(len(closedDate)): closedDate[i].to_datetime(). However, none oft these loops would be meaningful as the values aren't saved in a list vor wherever, just calculated for nothing. And besides: such loops are best written with one thing I really linke in Python: for i, cd in enumerate(closedDate): ... - this provides you both the elements and the indices in your loop. Commented May 17, 2018 at 22:55

2 Answers 2

0
[x.to_pydatetime().date() for x in closedDate]

Note, however, that you've probably made some kind of mistake to end up with a numpy array containing a pandas datatype. pandas Series and DataFrames are better equipped to handle pandas-specific types than numpy arrays are.

Sign up to request clarification or add additional context in comments.

Comments

0

I'd expect numpy to provide this functionality via astype, so you would not even have to loop over the array explicitely:

dt_arr = closedDate.astype(np.datetime64)

check:

closedDate
Out: 
array([Timestamp('2017-09-25 14:39:00'), Timestamp('2017-09-26 14:39:00'),
   Timestamp('2017-09-27 14:39:00')], dtype=object)

type(closedDate)
Out: numpy.ndarray

type(closedDate[0])
Out: pandas._libs.tslib.Timestamp

type(dt_arr)
Out: numpy.ndarray

type(dt_arr[0])
Out: numpy.datetime64

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.