在POSIXct中转换日期时间会给出错误的结果吗?

Pau*_*yuk 7 time r

我正在从数据库中提取数据,并通过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"
Run Code Online (Sandbox Code Playgroud)

显然foo和bar在数值上是相同的,但是R认为foo需要显示为BST并且显示为UTC.如何将两者显示为BST.这也不起作用;

as.POSIXct(bar, tz="BST")   #still gives "2011-04-04 13:18:58 UTC"
Run Code Online (Sandbox Code Playgroud)

Jos*_*ich 13

这是正在发生的事情. 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>
Run Code Online (Sandbox Code Playgroud)

您提供作为POSIXct对象的原点.这意味着调度中的as.POSIXct调用,定义为:as.POSIXct.numericas.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>
Run Code Online (Sandbox Code Playgroud)

x是一个POSIXct类对象(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"
Run Code Online (Sandbox Code Playgroud)