gpt4 book ai didi

R strftime() 行为

转载 作者:行者123 更新时间:2023-12-04 11:28:37 29 4
gpt4 key购买 nike

下面列出了两行代码。两者对日期和时间的期望相同,但只有一个有效。我正在使用 R 3.1。

以下不起作用:

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

返回以下错误:
Error in as.POSIXlt.character(x, tz = tz) : 
character string is not in a standard unambiguous format

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

二线店铺 DateTime2正如预期的那样。

有什么想法吗?

最佳答案

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

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

它调用 as.POSIXlt然后使用参数 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

原因是 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>

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

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

Value

The format methods and strftime return character vectors representing the time.



做你想做的事,使用 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"

编辑:仅供引用,您的第二行代码也不起作用:
strftime("08/02/2010 06:50:29.450", format="%m/%d/%Y %H:%M:%OS", tz="GMT")
[1] "02/20/0008 00:00:00"

关于R strftime() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25299544/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com