首页 文章

将R数据帧写入excel文件时,时间戳会发生变化,具体取决于UTC偏移量

提问于
浏览
0

我正在尝试将数据帧写入excel文件 . 示例数据帧如下所示 . 由于时间戳是 factor 类,我使用lubridate包将其转换为 POSIXct 格式 .

library(lubridate)
library(xlsx)
df=structure(list(ts = structure(c(5L, 8L, 9L, 1L, 6L, 7L, 4L, 2L, 3L),
 .Label = c("01.09.2016 10:56:56", "01.09.2016 11:04:37", 
"01.09.2016 12:03:59", "02.09.2016 08:47:01", "30.08.2016 08:27:28", 
"30.08.2016 16:08:56", "31.08.2016 07:38:43", "31.08.2016 10:26:53",
"31.08.2016 10:37:40"), class = "factor")), .Names = "ts", 
row.names = c(NA,-9L), class = "data.frame")
df$ts = as.POSIXct(strptime(df$ts, "%d.%m.%Y %H:%M:%S"))
write.xlsx(df, "output.xlsx", sheetName="output")

当我尝试使用 write.xlsx 命令将数据帧写入excel文件时,我得到一个输出,其中时间戳与原始时间不同 .
R dataframe and excel output

可以观察到时间偏移了两个小时 . 我住在属于UTC时间02:00的区域 . 这可能是影响变化的因素吗?如果是这样,有没有办法阻止Excel根据UTC偏移更改时间信息?

1 回答

  • 0

    R数据帧中的数据与时区CEST一致 . 写入excel时,excel会自动将时区更改为GMT,从而导致excel中的时移 . 一种解决方法是使用 force_tz 将R中的时区更改为GMT而不更改时间数据 .

    df$ts = as.POSIXct(strptime(df$ts, "%d.%m.%Y %H:%M:%S"))
    Sys.setenv(TZ="")    
    df$ts = force_tz(df$ts,tzone="GMT")
    write.xlsx(df, "output.xlsx", sheetName="output")
    

相关问题