简体   繁体   中英

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?

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')

The previous code no more works in the recent versions of numpy.

TypeError: Cannot get a common metadata divisor for NumPy datetime metadata [D] and [M] because they have incompatible nonlinear base time units
import numpy as np #version: 1.18.5
import pandas as pd #version: 1.1.5
df['duration'] = (df['end'] - df['start']).astype('timedelta64[M]')/np.timedelta64(1, 'M')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM