volatile
volatile

Reputation: 949

Pandas timestamp on array

Pandas does not convert my array into an array of Timestamps:

a = np.array([1457392827660434006, 1457392828660434012,  1457392829660434023,1457474706167386148])
pd.Timestamp(a)

gives an an error :

TypeError                                 Traceback (most recent call last)
<ipython-input-42-cdf0e494942d> in <module>()
      1 a = np.array([1457392827660434006, 1457392828660434012, 1457392829660434023,1457474706167386148])
----> 2 pd.Timestamp(a)

pandas/tslib.pyx in pandas.tslib.Timestamp.__new__ (pandas/tslib.c:8967)()

pandas/tslib.pyx in pandas.tslib.convert_to_tsobject (pandas/tslib.c:23508)()

TypeError: Cannot convert input to Timestamp

Whereas looping on the array elements works just fine :

for i in range(4):
    t = pd.Timestamp(a[i])
    print t

gives :

2016-03-07 23:20:27.660434006
2016-03-07 23:20:28.660434012
2016-03-07 23:20:29.660434023
2016-03-08 22:05:06.167386148

As expected.

Moreover when that array is my first column in a csv file, it does not get parsed to a TimeStamp automatically, even if I specify parse_date correctly.

Any help please?

Upvotes: 5

Views: 3607

Answers (1)

jezrael
jezrael

Reputation: 862641

I think you can use to_datetime and then if you need array values:

import pandas as pd
import numpy as np

a = np.array([1457392827660434006, 1457392828660434012,  
              1457392829660434023,1457474706167386148])

print pd.to_datetime(a).values

['2016-03-08T00:20:27.660434006+0100' '2016-03-08T00:20:28.660434012+0100'
 '2016-03-08T00:20:29.660434023+0100' '2016-03-08T23:05:06.167386148+0100']

print pd.to_datetime(a, unit='ns').values
['2016-03-08T00:20:27.660434006+0100' '2016-03-08T00:20:28.660434012+0100'
 '2016-03-08T00:20:29.660434023+0100' '2016-03-08T23:05:06.167386148+0100']

Upvotes: 3

Related Questions