I have :
excessmove_start = '2015-1-6'
I want to have a new variable called excess_graph
which is always 3 months ahead of excessmove_start
.
So, for this example, my expected output would be :
excess_graph = '2015-4-6'
I have :
excessmove_start = '2015-1-6'
I want to have a new variable called excess_graph
which is always 3 months ahead of excessmove_start
.
So, for this example, my expected output would be :
excess_graph = '2015-4-6'
This will do the job:
from datetime import datetime
from dateutil.relativedelta import relativedelta
excessmove_start = '2015-1-6'
s = datetime.strptime(excessmove_start, "%Y-%m-%d")
excess_graph= s+ relativedelta(months=+3)
print(excess_graph.strftime("%Y-%m-%d"))
This prints
2015-04-06
Let s
be a sample pd.Series
of stings that look like dates
dates = pd.date_range('2016-01-01', '2016-12-31')
s = pd.Series(np.sort(np.random.choice(dates, 10))).dt.strftime('%Y-%m-%d')
s
0 2016-01-08
1 2016-01-13
2 2016-02-08
3 2016-03-31
4 2016-04-02
5 2016-04-16
6 2016-06-07
7 2016-06-14
8 2016-10-13
9 2016-12-20
dtype: object
You can use pd.offsets
to add 3 months
pd.to_datetime(s) + pd.offsets.DateOffset(months=3)
0 2016-04-08
1 2016-04-13
2 2016-05-08
3 2016-06-30
4 2016-07-02
5 2016-07-16
6 2016-09-07
7 2016-09-14
8 2017-01-13
9 2017-03-20
dtype: datetime64[ns]
You can turn them back to strings
(pd.to_datetime(s) + pd.offsets.DateOffset(months=3)).dt.strftime('%Y-%m-%d')
0 2016-04-08
1 2016-04-13
2 2016-05-08
3 2016-06-30
4 2016-07-02
5 2016-07-16
6 2016-09-07
7 2016-09-14
8 2017-01-13
9 2017-03-20
dtype: object
We can smash it all together to see that it all works out
xs_start = pd.to_datetime(s)
offset = pd.offsets.DateOffset(months=3)
xs_graph = xs_start + offset
check = pd.DataFrame(dict(
excessmove_start=xs_start,
excess_graph=xs_graph,
delta=xs_graph - xs_start
))
check
delta excess_graph excessmove_start
0 91 days 2016-04-08 2016-01-08
1 91 days 2016-04-13 2016-01-13
2 90 days 2016-05-08 2016-02-08
3 91 days 2016-06-30 2016-03-31
4 91 days 2016-07-02 2016-04-02
5 91 days 2016-07-16 2016-04-16
6 92 days 2016-09-07 2016-06-07
7 92 days 2016-09-14 2016-06-14
8 92 days 2017-01-13 2016-10-13
9 90 days 2017-03-20 2016-12-20
Use relativedelta:
import dateutil
excessmove_start = date(2015,1,6)
excess_graph = excessmove_start + datetime.relativedelta.relativedelta(months=3))