pythontimedeltapython-datetime

Python Timedelta64 convert days to months


I have a Pandas dataframe with 2 columns representing a start-timestamp and an end-timestamp:

start       end
2016-06-13  2016-07-20

The datatype of these columns is datetime64[ns].

I now want to create a new column showing the difference in months:

start       end         duration
2016-06-13  2016-07-20  1.1

What I tried is to dow the following:

df['duration'] = df['end'] - df['start']

The result looks like this:

start       end         duration
2016-06-13  2016-07-20  37 days 00:00:00.000000000

I then tried to do the following:

df['duration'] = df['end'] - df['start']).dt.months

But this yields the following error

AttributeError: 'TimedeltaProperties' object has no attribute 'months'

The datatype of the duration column is timedelta64[ns].

How can I achieve the desired result?


Solution

  • import numpy as np #version: 1.16.2
    import pandas as pd #version: 0.25.1
    
    df['duration'] = (df['end'] - df['start'])/np.timedelta64(1, 'M')