import pandas as pd
import numpy as np
from datetime import datetime
def add_date(date):
d = date + np.timedelta64(months, 'M')
y = d.year
if d.is_leap_year:
y = y + 1 # Here you can add more conditions
return datetime(year=y, month=1, day=1)
#or return d + pd.offsets.DateOffset(years=1)
return datetime(year=y, month=d.month, day=d.day) #or d
df = pd.DataFrame({'date':['2019-01-03', '2018-01-01','2018-11-21','2017-05-01']})
months = 24
df['date'] = pd.to_datetime(df['date']).apply(add_date)
print(df)
# Or you can use by dayofyear attribute provide by pandas
def add_date(date):
d = date + np.timedelta64(months, 'M')
days = 0
if d.is_leap_year:
days = 367 - d.day_of_year
return date + np.timedelta64(months, 'M') + np.timedelta64(days, 'D')
Output
date
0 2021-01-02 #d = 2021-01-02 11:38:24 - Not leap year
1 2021-01-01 #d = 2020-01-01 11:38:24 - Leap year
2 2021-01-01 #d = 2020-11-20 11:38:24 - Leap year
3 2019-05-01 #d = 2019-05-01 11:38:24 - Not leap year
# where d=date+ np.timedelta64(24, 'M')
If you wish to check the date in dataframe, you can do following,
def add_date(date):
days = 0
if date.is_leap_year :
days = 367 - date.day_of_year
return date + np.timedelta64(months, 'M') + np.timedelta64(days, 'D')