Siraj S. Siraj S. - 2 months ago 32
Python Question

convert pandas timedelta output from days to quarter

here is my input:

import pandas as pd
dt_one = pd.to_datetime('2015/5/25') - pd.tseries.offsets.QuarterEnd()
dt_two = pd.to_datetime('2016/9/15') - pd.tseries.offsets.QuarterEnd()


here is my output:

(dt_two - dt_one)
Out[75]: Timedelta('457 days 00:00:00')


however, i desire to convert the above time delta from days in between two dates to quarters in between those two dates. How can I achieve this? The output should be '5'

Answer

You can calculate the number of quarters like this:

In [106]: dt_one = pd.to_datetime('2015/5/25') - pd.tseries.offsets.QuarterEnd()
     ...: dt_two = pd.to_datetime('2016/9/15') - pd.tseries.offsets.QuarterEnd()
     ...: 

In [107]: ((dt_two.year - dt_one.year)*12 + (dt_two.month - dt_one.month))/3.0
Out[107]: 5.0