Shaman74
Shaman74

Reputation: 11

Convert pandas datetime time difference values from days to years

I have a datetime value (date of an event) that I created by importing a date value from a csv file. I then tried to calculate that person's age by subtracting the datetime of the event from the datetime of their date of birth. This gives me an answer in days - but I'd like it in years.

To import the data from an excel csv file I used this:

Patients = pandas.read_csv("Patients_SN.csv", parse_dates=True) 
Patients['dateofbirth'] = pandas.to_datetime(Patients['dateofbirth'], format='%d/%m/%Y')

I then merged the patient data with another (event) dataset called Transitions3 so that each event has the person's date of birth in a column called 'dateofbirth'.

I've been able to get a number (in days) that represents the age of the person at the time of the event using the following:

Transitions3['AgeAtFirstEvent']=(Transitions3['FirstEventDate']-Transitions3['dateofbirth'])

As I said - this gives me the answer in days

1782 days 00:00:00.000000000

I've tried using the following code to change it to years

Transitions3['AgeAtFirstDial']= pandas.to_datetime(Transitions3['AgeAtFirstDial'], unit="y")

but I get this error: ValueError: cannot cast unit y

have also tried:

Transitions3['Age1stDial']=Transitions3['AgeAtFirstDial'].total_years()

but i get this:

Traceback (most recent call last):

  File "<ipython-input-22-3dc3b7338471>", line 1, in <module>
    Transitions3['Age1stDial']=Transitions3['AgeAtFirstDial'].total_years()

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 4376, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: 'Series' object has no attribute 'total_years'

Any suggestions? Thanks in advance.

Upvotes: 1

Views: 2473

Answers (1)

kerwei
kerwei

Reputation: 1842

I think the output of the subtraction is a timedelta series. In that case, you can convert it with the following.

Transitions3['AgeAtFirstEvent'] / np.timedelta64(1, 'Y')

You can read more about it here.

Upvotes: 2

Related Questions