88

我有两个日期让我们说14.01.201326.03.2014

我想根据周(?)、月(在示例 14 中)、季度(4)和年(1)来获得这两个日期之间的差异。

你知道得到这个的最好方法吗?

4

9 回答 9

80

那这个呢:

# get difference between dates `"01.12.2013"` and `"31.12.2013"`

# weeks
difftime(strptime("26.03.2014", format = "%d.%m.%Y"),
strptime("14.01.2013", format = "%d.%m.%Y"),units="weeks")
Time difference of 62.28571 weeks

# months
(as.yearmon(strptime("26.03.2014", format = "%d.%m.%Y"))-
as.yearmon(strptime("14.01.2013", format = "%d.%m.%Y")))*12
[1] 14

# quarters
(as.yearqtr(strptime("26.03.2014", format = "%d.%m.%Y"))-
as.yearqtr(strptime("14.01.2013", format = "%d.%m.%Y")))*4
[1] 4

# years
year(strptime("26.03.2014", format = "%d.%m.%Y"))-
year(strptime("14.01.2013", format = "%d.%m.%Y"))
[1] 1

as.yearmon()并且as.yearqtr()在包装中zooyear()在包装中lubridate。你怎么看?

于 2013-01-22T09:28:59.407 回答
61

所有现有的答案都是不完美的(IMO),要么对所需的输出做出假设,要么不为所需的输出提供灵活性。

根据 OP 的示例和 OP 声明的预期答案,我认为这些是您正在寻找的答案(加上一些易于推断的其他示例)。

(这只需要基础 R,不需要 zoo 或 lubridate)

转换为日期时间对象

date_strings = c("14.01.2013", "26.03.2014")
datetimes = strptime(date_strings, format = "%d.%m.%Y") # convert to datetime objects

天数差异

您可以在几天内使用差异来获得我们以后的一些答案

diff_in_days = difftime(datetimes[2], datetimes[1], units = "days") # days
diff_in_days
#Time difference of 435.9583 days

周差

units = "weeks"周差是in的一个特例difftime()

diff_in_weeks = difftime(datetimes[2], datetimes[1], units = "weeks") # weeks
diff_in_weeks
#Time difference of 62.27976 weeks

请注意,这与将 diff_in_days 除以 7(一周 7 天)相同

as.double(diff_in_days)/7
#[1] 62.27976

年差

用类似的逻辑,我们可以从 diff_in_days 推导出年份

diff_in_years = as.double(diff_in_days)/365 # absolute years
diff_in_years
#[1] 1.194406

您似乎期望年的差异为“1”,所以我假设您只想计算绝对日历年或其他东西,您可以通过使用轻松地做到这一点floor()

# get desired output, given your definition of 'years'
floor(diff_in_years)
#[1] 1

季度差异

# get desired output for quarters, given your definition of 'quarters'
floor(diff_in_years * 4)
#[1] 4

月差

可以将其计算为 diff_years 的转换

# months, defined as absolute calendar months (this might be what you want, given your question details)
months_diff = diff_in_years*12
floor(month_diff)
#[1] 14

我知道这个问题很老,但鉴于我刚才还必须解决这个问题,我想我会添加我的答案。希望能帮助到你。

于 2015-04-22T00:48:45.513 回答
14

数周以来,您可以使用函数difftime

date1 <- strptime("14.01.2013", format="%d.%m.%Y")
date2 <- strptime("26.03.2014", format="%d.%m.%Y")
difftime(date2,date1,units="weeks")
Time difference of 62.28571 weeks

difftime不适用于持续数周的持续时间。
以下是cut.POSIXt用于这些持续时间的非常次优的解决方案,但您可以解决它:

seq1 <- seq(date1,date2, by="days")
nlevels(cut(seq1,"months"))
15
nlevels(cut(seq1,"quarters"))
5
nlevels(cut(seq1,"years"))
2

然而,这是您的时间间隔所跨越的月数、季度数或年数,而不是以月、季度、年表示的时间间隔的持续时间(因为它们没有恒定的持续时间)。考虑到您对@SvenHohenstein 回答的评论,我认为您可以将nlevels(cut(seq1,"months")) - 1其用于您想要实现的目标。

于 2013-01-22T09:20:16.137 回答
14

我只是为另一个问题写了这个,然后在这里偶然发现。

library(lubridate)

#' Calculate age
#' 
#' By default, calculates the typical "age in years", with a
#' \code{floor} applied so that you are, e.g., 5 years old from
#' 5th birthday through the day before your 6th birthday. Set
#' \code{floor = FALSE} to return decimal ages, and change \code{units}
#' for units other than years.
#' @param dob date-of-birth, the day to start calculating age.
#' @param age.day the date on which age is to be calculated.
#' @param units unit to measure age in. Defaults to \code{"years"}. Passed to \link{\code{duration}}.
#' @param floor boolean for whether or not to floor the result. Defaults to \code{TRUE}.
#' @return Age in \code{units}. Will be an integer if \code{floor = TRUE}.
#' @examples
#' my.dob <- as.Date('1983-10-20')
#' age(my.dob)
#' age(my.dob, units = "minutes")
#' age(my.dob, floor = FALSE)
age <- function(dob, age.day = today(), units = "years", floor = TRUE) {
    calc.age = interval(dob, age.day) / duration(num = 1, units = units)
    if (floor) return(as.integer(floor(calc.age)))
    return(calc.age)
}

使用示例:

my.dob <- as.Date('1983-10-20')

age(my.dob)
# [1] 31

age(my.dob, floor = FALSE)
# [1] 31.15616

age(my.dob, units = "minutes")
# [1] 16375680

age(seq(my.dob, length.out = 6, by = "years"))
# [1] 31 30 29 28 27 26
于 2014-12-08T18:26:39.707 回答
6

这是一个解决方案:

dates <- c("14.01.2013", "26.03.2014")

# Date format:
dates2 <- strptime(dates, format = "%d.%m.%Y")

dif <- diff(as.numeric(dates2)) # difference in seconds

dif/(60 * 60 * 24 * 7) # weeks
[1] 62.28571
dif/(60 * 60 * 24 * 30) # months
[1] 14.53333
dif/(60 * 60 * 24 * 30 * 3) # quartes
[1] 4.844444
dif/(60 * 60 * 24 * 365) # years
[1] 1.194521
于 2013-01-22T08:51:52.763 回答
6

这里仍然缺少lubridate答案(虽然Gregor 的功能是建立在这个包上的)

lubridate时间跨度文档对于理解周期和持续时间之间的差异非常有帮助。我也喜欢lubridate 备忘单这个非常有用的线程

library(lubridate)

dates <- c(dmy('14.01.2013'), dmy('26.03.2014'))

span <- dates[1] %--% dates[2] #creating an interval object

#creating period objects 
as.period(span, unit = 'year') 
#> [1] "1y 2m 12d 0H 0M 0S"
as.period(span, unit = 'month')
#> [1] "14m 12d 0H 0M 0S"
as.period(span, unit = 'day')
#> [1] "436d 0H 0M 0S"

期间不接受以周为单位。但是您可以将持续时间转换为周数:

as.duration(span)/ dweeks(1)
#makes duration object (in seconds) and divides by duration of a week (in seconds)
#> [1] 62.28571

reprex 包(v0.3.0)于 2019 年 11 月 4 日创建

于 2019-11-04T16:34:08.583 回答
2

试试这个一个月的解决方案

StartDate <- strptime("14 January 2013", "%d %B %Y") 
EventDates <- strptime(c("26 March 2014"), "%d %B %Y") 
difftime(EventDates, StartDate) 
于 2013-01-22T08:50:50.460 回答
2

更“精确”的计算。也就是说,不完整的周/月/季度/年的周/月/季度/年数是该周/月/季度/年中日历天数的分数。例如,2016-02-22 和 2016-03-31 之间的月数是 8/29 + 31/31 = 1.27586

内嵌代码的解释

#' Calculate precise number of periods between 2 dates
#' 
#' @details The number of week/month/quarter/year for a non-complete week/month/quarter/year 
#'     is the fraction of calendar days in that week/month/quarter/year. 
#'     For example, the number of months between 2016-02-22 and 2016-03-31 
#'     is 8/29 + 31/31 = 1.27586
#' 
#' @param startdate start Date of the interval
#' @param enddate end Date of the interval
#' @param period character. It must be one of 'day', 'week', 'month', 'quarter' and 'year'
#' 
#' @examples 
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "month"), 15/29 + 1)
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "quarter"), (15 + 31)/(31 + 29 + 31))
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "year"), (15 + 31)/366)
#' 
#' @return exact number of periods between
#' 
numPeriods <- function(startdate, enddate, period) {

    numdays <- as.numeric(enddate - startdate) + 1
    if (grepl("day", period, ignore.case=TRUE)) {
        return(numdays)

    } else if (grepl("week", period, ignore.case=TRUE)) {
        return(numdays / 7)
    }

    #create a sequence of dates between start and end dates
    effDaysinBins <- cut(seq(startdate, enddate, by="1 day"), period)

    #use the earliest start date of the previous bins and create a breaks of periodic dates with
    #user's period interval
    intervals <- seq(from=as.Date(min(levels(effDaysinBins)), "%Y-%m-%d"), 
        by=paste("1",period), 
        length.out=length(levels(effDaysinBins))+1)

    #create a sequence of dates between the earliest interval date and last date of the interval
    #that contains the enddate
    allDays <- seq(from=intervals[1],
        to=intervals[intervals > enddate][1] - 1,
        by="1 day")

    #bin all days in the whole period using previous breaks
    allDaysInBins <- cut(allDays, intervals)

    #calculate ratio of effective days to all days in whole period
    sum( tabulate(effDaysinBins) / tabulate(allDaysInBins) )
} #numPeriods

如果您发现上述解决方案不起作用的更多边界情况,请告诉我。

于 2018-01-03T06:26:03.130 回答
1

这是找出lubridate包中年份差异的简单方法:

as.numeric(as.Date("14-03-2013", format = "%d-%m-%Y") %--% as.Date("23-03-2014", format = "%d-%m-%Y"), "years")

这将返回 1.023956

floor()如果你不想要小数,你可以使用。

于 2021-04-29T19:43:51.200 回答