Zanam
Zanam

Reputation: 4807

Difference in years of array of Timestamp with today

I have an array of timestamps of size 500 as follows:

>>>TimeStampArray[0]
Timestamp('2017-02-20 14:00:19')

I want to find time difference of each element of that array with today's date and represent this output in days.

e.g. TimeStampArray[0] - today() = 3 days

I have tried using pandas datetimeindex with TimeStampArray but it keeps failing to convert to a format which I can then apply timedelta function to.

Edit:

type(TimeStampArray.dtypes)
<type 'numpy.dtype'>

head() give error: 'numpy.ndarray' object has no attribute 'head'

I just printed entire array and the contents look as:

   '2010-12-21T22:00:10.000000000', '2014-11-02T00:00:17.000000000',
   '2014-07-14T15:00:11.000000000', '2010-12-31T12:00:18.000000000',
   '2010-12-20T00:00:33.000000000', '2010-12-20T00:00:33.000000000'], dtype='datetime64[ns]')

Upvotes: 2

Views: 407

Answers (2)

jezrael
jezrael

Reputation: 863501

I think you can use abs with TimedeltaIndex.days:

rng = pd.date_range('2015-02-24', periods=10).values
print (rng)
['2015-02-24T00:00:00.000000000' '2015-02-25T00:00:00.000000000'
 '2015-02-26T00:00:00.000000000' '2015-02-27T00:00:00.000000000'
 '2015-02-28T00:00:00.000000000' '2015-03-01T00:00:00.000000000'
 '2015-03-02T00:00:00.000000000' '2015-03-03T00:00:00.000000000'
 '2015-03-04T00:00:00.000000000' '2015-03-05T00:00:00.000000000']

today = pd.datetime.now()
print (today)
2017-02-24 22:09:25.162455

print (abs(pd.DatetimeIndex(rng) - today).days)
[731 730 729 728 727 726 725 724 723 722]

Upvotes: 1

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210972

your TimeStampArray seems to be a NumPy array - IMO it's much easier to work with Pandas series:

In [178]: TimeStampArray
Out[178]:
array(['2010-12-21T22:00:10.000000000', '2014-11-02T00:00:17.000000000', '2014-07-14T15:00:11.000000000', '2010-12-31T12:00:18.000000000', '
2010-12-20T00:00:33.000000000',
       '2010-12-20T00:00:33.000000000'], dtype='datetime64[ns]')

In [179]: (pd.datetime.now() - pd.Series(TimeStampArray)).dt.days
Out[179]:
0    2256
1     845
2     956
3    2247
4    2258
5    2258
dtype: int64

Upvotes: 1

Related Questions