Home > Back-end >  How to calculate number of days between 2 months in Python
How to calculate number of days between 2 months in Python

Time:04-22

I have a requirement where I have to find number of days between 2 months where 1st month value is constant and 2nd month value is present in a data frame.

I have to subtract 24th Feb with values present in the Data Frame.

past_2_month = date.today()
def to_integer(dt_time):
    return 1*dt_time.month
past_2_month = to_integer(past_2_month)
past_2_month_num = past_2_month-2
day = 24
date_2 = dt.date(year, past_2_month_num, day)
date_2

Output of above code: datetime.date(2022, 2, 24)

Other values present in the Data frame is below:

dict_1 = {'Col1' : ['2017-05-01', np.NaN, '2017-11-01', np.NaN, '2016-10-01']}
a = pd.DataFrame(dict_1)

How to subtract this 2 values so that I can get difference in days between these 2 values?

CodePudding user response:

If need number of days between datetime column and 2 months shifted values use offsets.DateOffset and convert timedeltas to days by Series.dt.days:

a['Col1'] = pd.to_datetime(a['Col1'])
a['new'] = (a['Col1'] - (a['Col1'] - pd.DateOffset(months=2))).dt.days
print (a)
        Col1   new
0 2017-05-01  61.0
1        NaT   NaN
2 2017-11-01  61.0
3        NaT   NaN
4 2016-10-01  61.0

If need difference by another datetime solution is simplier - subtract and convert values to days:

a['Col1'] = pd.to_datetime(a['Col1'])
a['new'] = (pd.to_datetime('2022-02-24') - a['Col1']).dt.days
print (a)
        Col1     new
0 2017-05-01  1760.0
1        NaT     NaN
2 2017-11-01  1576.0
3        NaT     NaN
4 2016-10-01  1972.0
  • Related