2

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'
Dadep
  • 2,796
  • 5
  • 27
  • 40
thomas.mac
  • 1,236
  • 3
  • 17
  • 37
  • This link asks a very similar question, may help you out https://stackoverflow.com/questions/9594282/how-do-you-add-3-months-to-a-datetime-date-object-in-python – Jake Jul 21 '17 at 19:44

3 Answers3

2

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
Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
1

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
piRSquared
  • 285,575
  • 57
  • 475
  • 624
0

Use relativedelta:

import dateutil

excessmove_start = date(2015,1,6)
excess_graph = excessmove_start + datetime.relativedelta.relativedelta(months=3))
asiviero
  • 1,225
  • 10
  • 16