我有一个大型数据帧,其中有一列包含日期时间,编码为因子变量。我的 Sys.timezone(( 是"欧洲/柏林"。日期时间具有以下格式:
2015-05-05 17:27:04+05:00
其中 +05:00 表示从格林威治标准时间开始的时移。重要的是,我的数据集中有多个时区,因此我无法设置特定的时区并忽略字符串的最后 6 个字符。这是我到目前为止尝试过的:
# Test Date
test <- "2015-05-05 17:27:04+05:00"
# Removing the ":" to make it readable by %z
A <- paste(substr(test,1,22),substr(test,24,25),sep = "");A
# Returns
# "2015-05-05 17:27:04+0500"
output <- as.POSIXct(as.character(A, "%Y-%B-%D %H:%M:%S%z"))
# Returns
# "2015-05-05 17:27:04 CEST"
+0500 的"CEST"输出不正确。此外,当我在整个列上运行此代码时,我看到每个日期都编码为 CEST,无论偏移量如何。
转换为 POSIXct 时如何保留指定的时区?
为了
方便这个过程,你可以使用lubridate
包。 例如
library("lubridate")#load the package
ymd_hms("2015-05-05 17:27:04+05:00",tz="GMT")#set the date format
[1] "2015-05-05 12:27:04 GMT"
因此,您保留时区信息。最后:
as.POSIXct(ymd_hms("2015-05-05 17:27:04+05:00",tz="GMT"),tz = "GMT")#transform the date into another timezone
[1] "2015-05-05 12:27:04 GMT"