user3084006
user3084006

Reputation: 5564

Python Time differencing in pandas

Lets say I have an array of date:

df=pd.DataFrame({'Date': [ '5/4/1985', '6/13/1983', '6/13/1982', '12/28/1987'], 'Name': ['J','K','L','M']})

and I want to find the difference between them and today in years, weeks, or quarters (four in one year).

So far I know I would use pd.datetime.now() to represent today.

Upvotes: 2

Views: 667

Answers (1)

CT Zhu
CT Zhu

Reputation: 54340

To get the number of nano second difference, Just do:

In [60]:
pd.datetime.now()-pd.to_datetime(df['Date'])
Out[60]:
0   10508 days, 15:56:08.609000
1   11199 days, 15:56:08.609000
2   11564 days, 15:56:08.609000
3    9540 days, 15:56:08.609000
Name: Date, dtype: timedelta64[ns]

To get the difference in days or years (etc):

q=pd.datetime.now()-pd.to_datetime(df['Date'])
array(q).astype('timedelta64[D]').astype(int) #in days
array(q).astype('timedelta64[Y]').astype(int) #in years

Upvotes: 2

Related Questions