使用lubridate创建新的日期时间组件时,时区将丢失

使用lubridate创建新的日期时间组件时,时区将丢失,r,dplyr,lubridate,tibble,R,Dplyr,Lubridate,Tibble,以下数据帧来自dput。我在datatime上使用了forced_tz,没有参数。我住在UTC+1时区 library(lubridate) library(dplyr) df <- structure(list(value = structure(c(1514967058, 1515148132, 1517472989, 1543844646, 1525085884, 1520584330, 1522838681, 1540379051, 1516707360, 1516705706)

以下数据帧来自
dput
。我在datatime上使用了
forced_tz
,没有参数。我住在UTC+1时区

library(lubridate)
library(dplyr)

df <- structure(list(value = structure(c(1514967058, 1515148132, 1517472989, 1543844646, 1525085884, 1520584330, 1522838681, 1540379051, 1516707360, 1516705706), 
                                 class = c("POSIXct", "POSIXt"))), 
          .Names = "value", 
          row.names = c(NA, -10L), 
          class = c("tbl_df", "tbl", "data.frame"))


    tz(df$value)
[1] ""

df2 <- df %>% 
  mutate(year=year(value))


    > tz(df2$year)
[1] "UTC"
库(lubridate)
图书馆(dplyr)
df tz(df2$年)
[1] “UTC”

我也曾使用过
tz=“Europe/Paris”
,但当我从日期时间(
day
month
等等)中删除某些内容时,它们会释放时区,再次使用UTC。是否可以将时区设置一次,然后将其转移到我创建的所有新datetime组件中

问题在于
year()
似乎返回了一个
数值
,因此它不再是
日期
对象

这是以下各项的默认方法:

因此,当您调用
tz(y)
时,由于它是数值型的,所以它没有
tz
属性,默认情况下,它被指定为
“UTC”


一个简单的解决方案是为自己设置时区:

attr(y, "tzone") <- Sys.timezone()
y
#[1] 2018
#attr(,"tzone")
#[1] "Europe/Berlin"

我建议您不要这样做,但您也可以修改以下默认方法:

myutz
y <- as.POSIXlt("2018-01-03 09:10:58 CET", tz = Sys.timezone())$year + 1900
#y
#[1] 2018
class(y)
#[1] "numeric"
# example:
# tz(123)
# [1] "UTC"
attr(y, "tzone") <- Sys.timezone()
y
#[1] 2018
#attr(,"tzone")
#[1] "Europe/Berlin"
tz(y)
[1] "Europe/Berlin"
my_tz <- function(x) {
  tzone <- attr(x, "tzone")[[1]]
  if (is.null(tzone) && !is.POSIXt(x))
    return(Sys.timezone()) # original was "UTC"
  if (is.character(tzone) && nzchar(tzone))
    return(tzone)
  tzone <- attr(as.POSIXlt(x[1]), "tzone")[[1]]
  if (is.null(tzone))
    return(Sys.timezone()) # original was "UTC"
  tzone
}

my_tz(y)
#[1] "Europe/Berlin"