gpt4 book ai didi

r - 在 POSIXct 中转换日期时间会产生奇怪的结果?

转载 作者:行者123 更新时间:2023-12-04 10:11:13 24 4
gpt4 key购买 nike

我正在从数据库中提取数据,并通过 rehsape2 运行结果。出于某种原因,这是将 POSIXct 日期时间戳转换为数字。没问题,我想,你可以把它们转回去,除非我有一个小时的时间。

这是一个最小的例子

foo<-as.POSIXct("2011-04-04 14:18:58")
as.numeric(foo) #gives 130192318
bar<-as.POSIXct(as.numeric(foo),
tz=Sys.timezone(),
origin=as.POSIXct(
strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC")))
as.numeric(bar) #gives 130192318 identical !
foo #Gives "2011-04-04 14:18:58 BST"
bar #Gives "2011-04-04 13:18:58 UTC"

显然 foo 和 bar 在数字上是相同的,但 R 认为 foo 需要显示为 BST,bar 显示为 UTC。如何将两者都显示为 BST。这也不起作用;
as.POSIXct(bar, tz="BST")   #still gives "2011-04-04 13:18:58 UTC"

最佳答案

这是发生了什么。 bar是使用 as.POSIXct.numeric 创建的,定义为:

as.POSIXct.numeric
function (x, tz = "", origin, ...)
{
if (missing(origin))
stop("'origin' must be supplied")
as.POSIXct(origin, tz = tz, ...) + x
}
<environment: namespace:base>

您提供的来源是 POSIXct目的。这意味着 as.POSIXct调用 as.POSIXct.numeric发送至 as.POSIXct.default ,定义为:
as.POSIXct.default
function (x, tz = "", ...)
{
if (inherits(x, "POSIXct"))
return(x)
if (is.character(x) || is.factor(x))
return(as.POSIXct(as.POSIXlt(x, tz, ...), tz, ...))
if (is.logical(x) && all(is.na(x)))
return(.POSIXct(as.numeric(x)))
stop(gettextf("do not know how to convert '%s' to class \"POSIXct\"",
deparse(substitute(x))))
}
<environment: namespace:base>
xPOSIXct类对象(您在初始调用中提供的 origin),因此它被简单地返回并且 tz=参数被忽略。

更新:
以下是如何转换 foo返回 POSIXct与适当的时区。
(foo <- as.POSIXct("2011-04-04 14:18:58", tz="GB"))
# [1] "2011-04-04 14:18:58 BST"
.POSIXct(as.numeric(foo), tz="GB")
# [1] "2011-04-04 14:18:58 BST"

关于r - 在 POSIXct 中转换日期时间会产生奇怪的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7257263/

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