Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add (subtract) months without exceeding the last day of the new month

Tags:

date

r

lubridate

I am looking to add and subtract six months (bond time) reliably with lubridate.

For example, adding six months to 12/31/2014 should result in 6/30/2015, and adding to 2/28/2014 should result in 8/31/2014

The issue with as.Date("2014-12-31") + months(6), is that it yields an NA. Alternatively, the second result is 8/28/2014 because it doesn't just add 6 months to the month and then know where the day should end up dependent upon the month.

Is there any way to quickly correct this? At the moment, I am building a function to basically use a switch and consider each month, but this is very long and I am having problems with it as well.

Thanks!

like image 659
Michael Clinton Avatar asked Mar 25 '14 08:03

Michael Clinton


People also ask

How do I subtract months and months in Excel?

You can use the EDATE function to quickly add or subtract months from a date. The EDATE function requires two arguments: the start date and the number of months that you want to add or subtract. To subtract months, enter a negative number as the second argument. For example, =EDATE("9/15/19",-5) returns 4/15/19.

How do you subtract months in pandas?

Subtract months from a date in Python using PandasPandas provide a class DateOffset, to store the duration or interval information. It is mostly used to increment or decrement a timestamp. It can be used with datetime module to to subtract N months from a date.

How do you subtract a month in Python?

The easiest way to subtract months from a date in Python is to use the dateutil extension. The relativedelta object from the dateutil. relativedelta module allows you to subtract any number of months from a date object.


1 Answers

The lubridate function %m+% may be useful here:

Add and subtract months to a date without exceeding the last day of the new month

as.Date("2014-12-31") %m+% months(6) # [1] "2015-06-30" 

To also handle the second case, you will need to round up to nearest month using ceiling_date, and subtract one day using days.

ceiling_date(as.Date("2014-02-28") %m+% months(6), unit = "month") - days(1) # [1] "2014-08-31" 
like image 155
Henrik Avatar answered Sep 21 '22 20:09

Henrik