gpt4 book ai didi

r - 将 R 数据帧写入 excel 文件时,时间戳会根据 UTC 偏移量发生变化

转载 作者:行者123 更新时间:2023-12-04 21:58:31 26 4
gpt4 key购买 nike

我正在尝试将数据框写入 excel 文件。示例数据框如下所示。由于时间戳属于 factor 类, 我把它转换成 POSIXct使用 lubridate 包进行格式化。

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偏移量更改时间信息?

最佳答案

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

关于r - 将 R 数据帧写入 excel 文件时,时间戳会根据 UTC 偏移量发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39413379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com