2

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

is there a way to get years, quarters or weeks instead of days
Sorry, the default is not in days but in nanoseconds. Corrected that. I don't know if you can get quarters, there are 4 types available for timedelta64: D W M Y, for day, week, month and year respectively.
So I guess the only way to change it to quarters is to change to months then divide by 3?
I guess that will be better (than calculated it from the number of weeks or days). There may be more elegant way of doing it, I don't know.

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.