计算两个日期间隔之间的每月天数 [英] Calculating days per month between interval of two dates

查看:128
本文介绍了计算两个日期间隔之间的每月天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组事件,每个事件都有一个开始和结束日期,但它们发生在几个月的范围内。我想创建一个表,显示此活动每月的天数。



我有以下例子。

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

我希望得到一个表如下:

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


Jochem

解决方案

这不一定是有效的,因为它创建一个顺序的日子,但它的工作:

 >图书馆(动物园)
>表(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

如果你的时间跨度比这个方法太慢,你必须创建一个序列的第一个月在你的两个(截断)日期之间,采取 diff ,并为终点做一点额外的工作。


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

解决方案

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.

这篇关于计算两个日期间隔之间的每月天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆