R 与as.difftime不一致

R 与as.difftime不一致,r,R,我可以将包含小时、分钟或秒规格的字符串转换为difftime: > as.difftime("12 h", "%H") Time difference of 12 hours > as.difftime("12 m", "%M") Time difference of 12 mins > as.difftime("12 s", "%S") Time difference of 12 secs > as.difftime("12 w", "%…") 但是我不能使用wee

我可以将包含小时、分钟或秒规格的字符串转换为
difftime

> as.difftime("12 h", "%H")
Time difference of 12 hours
> as.difftime("12 m", "%M")
Time difference of 12 mins
> as.difftime("12 s", "%S")
Time difference of 12 secs
> as.difftime("12 w", "%…")
但是我不能使用week规范,因为没有合适的格式…,尽管
“week”
difftime
的合法单位:

> as.difftime("12 h", "%H")
Time difference of 12 hours
> as.difftime("12 m", "%M")
Time difference of 12 mins
> as.difftime("12 s", "%S")
Time difference of 12 secs
> as.difftime("12 w", "%…")
我忽略了什么吗?

罗兰指出:


它不能工作超过几个小时…很明显,如果你研究代码的话。相关部分是

difftime(strptime(tim, format = format), strptime("0:0:0", format = "%X"), units = units)
。如果只为
strtime
指定时间,则会添加当前日期

实际上,在R控制台中学习代码很容易:

> as.difftime
function (tim, format = "%X", units = "auto") 
{
    if (inherits(tim, "difftime")) 
        return(tim)
    if (is.character(tim)) {
        difftime(strptime(tim, format = format), strptime("0:0:0", 
            format = "%X"), units = units)
    }
    else {
        if (!is.numeric(tim)) 
            stop("'tim' is not character or numeric")
        if (units == "auto") 
            stop("need explicit units for numeric conversion")
        if (!(units %in% c("secs", "mins", "hours", "days", "weeks"))) 
            stop("invalid units specified")
        .difftime(tim, units = units)
    }
}
问题的关键在于,使用
strtime
会导致指定给
as.difftime
的时间间隔字符串被视为一个时间点,从该时间点开始,0小时的 减去当前日期。由于各种原因,这使得带有字符串的
作为.difftime
在几天和几周内不可用,例如,strtime不接受0天的值,尽管它作为间隔是完全有效的


关于R-devel邮件列表的评论请求没有得到广泛的响应。(我通过私人邮件从Emil Bode那里收到了一些有价值的想法,因此我不会在这里复制它们。)因此,我不会建议将
更改为.difftime
,也因为更改它会导致R版本之间的差异。

它在几个小时后无法工作。如果您研究代码,为什么应该是显而易见的。相关部分是
difftime(strtime(tim,format=format),strtime(“0:0:0”,format=“%X”),units=units)
。如果只为
strtime
指定时间,则会添加当前日期。如果你只指定日期的一部分,它会做一些令人惊讶的事情,特别是在几周内。@Roland-我没有想到我能多么容易地学习代码。如果你把你的评论写进回复,我可以接受。事实上,我认为你应该把这件事提请R-devel邮件列表的注意。我认为这至少是一个文件问题。但也许R-core甚至可以修复它。@Roland-好的,我会的。