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

时间:2016-09-09 14:01:23

标签: r excel r-xlsx

我正在尝试将数据帧写入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 :(得分:1)

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")