Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating days per month between interval of two dates

Tags:

date

r

intervals

I have a set of events that each have a start and end date, but they take place over the scope of a number of months. I would like to create a table that shows the number of days in each month for this event.

I have the following example.

event_start_date <- as.Date("23/10/2012", "%d/%m/%Y")
event_end_date   <- as.Date("07/02/2013", "%d/%m/%Y")

I would expect to get a table out as the following:

Oct-12  8
Nov-12  30
Dec-12  31
Jan-13  31
Feb-13  7

Does anybody know about a smart and elegant way of doing this or is creating a system of loops the only viable method?

Jochem

like image 542
Jochem Avatar asked Nov 08 '12 11:11

Jochem


People also ask

How do you calculate days months between two dates?

Calculate elapsed days/month/years To calculate elapsed days is so easy, you just need to apply this formula = B2-A2, A2 is the start date, B2 is the end date. Tip: To calculate elapsed month, you can use this formula =DATEDIF(A2,B2,"m"), A2 is the start date, B2 is the end date.

How do I calculate days intervals in Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered. Note that Excel recognizes leap years.


2 Answers

This is not necessarily efficient because it creates a sequence of days, but it does the job:

> library(zoo)
> table(as.yearmon(seq(event_start_date, event_end_date, "day")))

Oct 2012 Nov 2012 Dec 2012 Jan 2013 Feb 2013 
       9       30       31       31        7

If your time span is so large than this method is slow, you'll have to create a sequence of firsts of the months between your two (truncated) dates, take the diff, and do a little extra work for the end points.

like image 127
flodel Avatar answered Sep 30 '22 00:09

flodel


As DjSol already pointed out in his comment, you can just subtract two dates to get the number of days:

event_start_date <- as.Date("23/10/2012", "%d/%m/%Y")
event_end_date   <- as.Date("07/02/2013", "%d/%m/%Y")
as.numeric(event_end_date - event_start_date)

Is that what you want? I have the feeling that you might have more of a problem to get the start and end date in such a format so you can easily subtract them because you mention a loop. If so, however, I guess we need more details on how your actual data looks.

like image 37
Christoph_J Avatar answered Sep 30 '22 01:09

Christoph_J