Search code examples
pythondataframedatetimegoogle-colaboratorytimedelta

Convert timedelta of days into years


I have a timedelta64[ns] column (final_df['Age']) in a dataframe, created by subtracting a <class 'pandas._libs.tslibs.timestamps.Timestamp'> column (final_df["Contact Birth Date"]) from a datetime64[ns] variable (today_date). However, when I print the dataframe, it shows the timedelta in the number of days, like so:

5511 days

I want it to print just the number of years. I have not had any luck converting it to an int or a datetime object. Is there a way to convert the '5511 days' to '15 years' or just '15'? If it helps, I am using google colab.

Here is my code for today_date and final_df['Age']. I imported datetime as dt.

today_date = pd.to_datetime(dt.date.today())
final_df['Age'] = today_date - final_df["Contact Birth Date"]

Solution

  • I can help you, check this out- > timedelta(days=5511).days this returns days in int and then you can divide it to 365 and you will take years. timedelta(days=5511).days/365 .