Behavior of R strftime ()

Two lines of code are listed below. Both are identical for day and time, but only one works. I am using R 3.1.

The following does not work:

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

It returns the following error:

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

But the following works:

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

The second line saves DateTime2as expected.

Any thoughts?

+4
source share
2 answers

What happens if you use strftime? Here is the code strftime:

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

It calls the format as.POSIXltand THEN using the argument format. If you call directly as.POSIXltin your example without providing an argument format, this is what happens:

> 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

The reason is because the code for the as.POSIXltfollowing:

> 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>

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"

: FYI :

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

, , strftime. - POSIXt . POSIXt strftime. , POSIXlt . , format - , , . :

strftime(as.POSIXct("2014-10-20 12:14:50"), format = "%Y/%m")
#[1] "2014/10"

? , strftime POSIXlt , - . 13, . 12 , . , ( , ).

+1

All Articles