R strftime()行为

R_i*_*eat 4 datetime r

下面列出了两行代码.两者对于白天和时间都是相同的,但只有一个有效.我正在使用R 3.1.

以下不起作用:

DateTime2=strftime("08/13/2010 05:26:24.350", format="%m/%d/%Y %H:%M:%OS", tz="GMT")
Run Code Online (Sandbox Code Playgroud)

返回以下错误:

Error in as.POSIXlt.character(x, tz = tz) : 
  character string is not in a standard unambiguous format
Run Code Online (Sandbox Code Playgroud)

但以下工作:

DateTime2=strftime("08/02/2010 06:50:29.450", format="%m/%d/%Y %H:%M:%OS", tz="GMT")
Run Code Online (Sandbox Code Playgroud)

第二行DateTime2按预期存储.

有什么想法吗?

pla*_*pus 7

使用时会发生什么strftime?这是strftime代码:

> strftime
function (x, format = "", tz = "", usetz = FALSE, ...) 
format(as.POSIXlt(x, tz = tz), format = format, usetz = usetz, 
    ...)
<bytecode: 0xb9a548c>
<environment: namespace:base>
Run Code Online (Sandbox Code Playgroud)

as.POSIXlt使用参数调用和THEN格式format.如果你直接调用as.POSIXlt你的例子而不给出一个参数format,那么会发生以下情况:

> as.POSIXlt("08/13/2010 05:26:24.350", tz="GMT")
Error in as.POSIXlt.character("08/13/2010 05:26:24.350", tz = "GMT") : 
  character string is not in a standard unambiguous format
Run Code Online (Sandbox Code Playgroud)

原因是代码as.POSIXlt如下:

> as.POSIXlt.character
function (x, tz = "", format, ...) 
{
    x <- unclass(x)
    if (!missing(format)) {
        res <- strptime(x, format, tz = tz)
        if (nzchar(tz)) 
            attr(res, "tzone") <- tz
        return(res)
    }
    xx <- x[!is.na(x)]
    if (!length(xx)) {
        res <- strptime(x, "%Y/%m/%d")
        if (nzchar(tz)) 
            attr(res, "tzone") <- tz
        return(res)
    }
    else if (all(!is.na(strptime(xx, f <- "%Y-%m-%d %H:%M:%OS", 
        tz = tz))) || all(!is.na(strptime(xx, f <- "%Y/%m/%d %H:%M:%OS", 
        tz = tz))) || all(!is.na(strptime(xx, f <- "%Y-%m-%d %H:%M", 
        tz = tz))) || all(!is.na(strptime(xx, f <- "%Y/%m/%d %H:%M", 
        tz = tz))) || all(!is.na(strptime(xx, f <- "%Y-%m-%d", 
        tz = tz))) || all(!is.na(strptime(xx, f <- "%Y/%m/%d", 
        tz = tz)))) {
        res <- strptime(x, f, tz = tz)
        if (nzchar(tz)) 
            attr(res, "tzone") <- tz
        return(res)
    }
    stop("character string is not in a standard unambiguous format")
}
<bytecode: 0xb9a4ff0>
<environment: namespace:base>
Run Code Online (Sandbox Code Playgroud)

如果没有format给出,它会尝试一个通用格式的系列,如果它们都不起作用,它会引发你得到的错误.

所有这一切的原因strftime(与此相反,strptime混淆)不是用于将字符转换为POSIXlt对象,而是将POSIXlt对象转换为字符.从帮助页面strftime:

格式方法和strftime返回表示时间的字符向量.

要做你想做的事,请as.POSIXlt直接使用如下:

> as.POSIXlt("08/13/2010 05:26:24.350", tz="GMT", format="%m/%d/%Y %H:%M:%OS")
[1] "2010-08-13 05:26:24 GMT"
Run Code Online (Sandbox Code Playgroud)

编辑:仅供参考,你的第二行代码也不起作用:

strftime("08/02/2010 06:50:29.450", format="%m/%d/%Y %H:%M:%OS", tz="GMT")
[1] "02/20/0008 00:00:00"
Run Code Online (Sandbox Code Playgroud)