R中的时区转换是否给出正确的值?
为了进行合理性检查,我想看看在从DST到ST的转换时间后几分钟,是否会给出相同的时间,用于等效的东部时间和UTC。 在加拿大,11月的第一个星期日,时间从凌晨2:00变为凌晨1:00。 为了简单起见,我只考虑2012年至2016年的1个时区 以下是复制数据的my代码:R中的时区转换是否给出正确的值?,r,timezone,posixct,R,Timezone,Posixct,为了进行合理性检查,我想看看在从DST到ST的转换时间后几分钟,是否会给出相同的时间,用于等效的东部时间和UTC。 在加拿大,11月的第一个星期日,时间从凌晨2:00变为凌晨1:00。 为了简单起见,我只考虑2012年至2016年的1个时区 以下是复制数据的my代码: require(timeDate) timezones <- data.frame(TZname=rep(c('America/Vancouver'),each=5)) timezones$TZname <- as.c
require(timeDate)
timezones <- data.frame(TZname=rep(c('America/Vancouver'),each=5))
timezones$TZname <- as.character(timezones$TZname)
timezones$DST_end <- paste(as.character(timeNthNdayInMonth(paste0(as.character(2012:2016), '-11-01'), nday=0, nth=1)), '1:00')
# initialize a column
timezones$ET_DST_end <- .POSIXct(integer(nrow(timezones)))
for (i in 1:nrow(timezones)) {
timezones$ET_DST_end[i] <- as.POSIXct(timezones$DST_end[i], tz=timezones$TZname[i])
}
timezones$UTC_DST_end <- format(timezones$ET_DST_end, tz='UTC')
dput(timezones)
# Below is the result
structure(list(TZname = c("America/Vancouver", "America/Vancouver",
"America/Vancouver", "America/Vancouver", "America/Vancouver"
), DST_end = c("2012-11-04 1:00", "2013-11-03 1:00", "2014-11-02 1:00",
"2015-11-01 1:00", "2016-11-06 1:00"), ET_DST_end = structure(c(1352016000,
1383465600, 1414915200, 1446364800, 1478419200), class = c("POSIXct",
"POSIXt")), UTC_DST_end = c("2012-11-04 08:00:00", "2013-11-03 08:00:00",
"2014-11-02 08:00:00", "2015-11-01 08:00:00", "2016-11-06 08:00:00"
)), .Names = c("TZname", "DST_end", "ET_DST_end", "UTC_DST_end"
), row.names = c(NA, -5L), class = "data.frame")
问题1:为什么会发生这种情况
问题2:这是否意味着时区转换不准确
问题3:UTC小时不是应该是9点而不是8点吗?因为凌晨1:00+8=9:00
谢谢我无法用您的代码重现您的结果,但这可能会有所帮助。类
POSIXct
(与POSIXlt
相同)的向量只能有一个时区
x <- as.POSIXct(c("2015-01-01", "2016-01-01"), tz = "GMT")
str(unclass(x))
# atomic [1:2] 1.42e+09 1.45e+09
# - attr(*, "tzone")= chr "GMT"
as.POSIXct("2015-01-01", tz = "America/Los_Angeles")
#[1] "2015-01-01 PST"
x[1] <- as.POSIXct("2015-01-01", tz = "America/Los_Angeles")
str(unclass(x))
# atomic [1:2] 1.42e+09 1.45e+09
# - attr(*, "tzone")= chr "GMT"
x请使用dput
提供数据。这将保持每列的格式和类别。时区问题很难解决。发布dput(head(timezones,15))
以便我们有一个坚实的基础来纠正您的错误(或者可能是错误识别,尽管这不太可能)。您能提供数据的dput
吗?R使用操作系统功能来处理日期时间和时区。请至少告诉我们您的地区、操作系统和R版本。发布sessionInfo()
的输出。谢谢@Roland。我添加了数据的sessionInfo输出。希望这有帮助。
x <- as.POSIXct(c("2015-01-01", "2016-01-01"), tz = "GMT")
str(unclass(x))
# atomic [1:2] 1.42e+09 1.45e+09
# - attr(*, "tzone")= chr "GMT"
as.POSIXct("2015-01-01", tz = "America/Los_Angeles")
#[1] "2015-01-01 PST"
x[1] <- as.POSIXct("2015-01-01", tz = "America/Los_Angeles")
str(unclass(x))
# atomic [1:2] 1.42e+09 1.45e+09
# - attr(*, "tzone")= chr "GMT"
function (x, ..., value)
{
if (!length(value))
return(x)
value <- unclass(as.POSIXct(value))
cl <- oldClass(x)
tz <- attr(x, "tzone")
class(x) <- NULL
x <- NextMethod(.Generic)
class(x) <- cl
attr(x, "tzone") <- tz
x
}