【问题标题】:Convert character and UTC offset to POSIXct in R将字符和UTC偏移量转换为R中的POSIXct
【发布时间】:2016-02-09 21:23:25
【问题描述】:

我在 R 中有以下数据:

times <- c("2015-03-08 00:00:00", "2015-03-08 01:00:00", "2015-03-08 02:00:00", "2015-03-08 03:00:00")
utcOffsets <- c(2, 1, 1, 1)
mydata <- data.frame(time=times, utcOffset=utcOffsets)

我表中的 utcOffset 列表示每个数据值的时区偏移量。当我尝试使用 strptime 函数将数据转换为 POSIXct 时,我遇到了问题。时间“2015-03-08 01:00:00”由于某种原因被转换为NA。

as.POSIXct(strptime(mydata$time, "%Y-%m-%d %H:%M:%S"))

[1] "2015-03-08 00:00:00 MST" "2015-03-08 01:00:00 MST" 不适用
[4] "2015-03-08 03:00:00 MDT"

我怀疑夏令时时间有问题,我必须在 strptime 函数中指定时区。如果我的所有数据的时区都是固定的,则以下代码适用于我:

as.POSIXct(strptime(mydata$time, "%Y-%m-%d %H:%M:%S", tz="Europe/Prague"))

[1] "2015-03-08 00:00:00 CET" "2015-03-08 01:00:00 CET" "2015-03-08 02:00:00 CET" [4] "2015-03-08 03:00:00 CET"

但是,在我的数据中,时区是在我的表格的 utcOffset 列中指定的,例如 utcOffset=1 表示 GMT+1 或 utcOffset=2 表示 GMT+2。当我尝试使用“GMT+n”格式的时区代码时,我收到一条警告:

as.POSIXct(strptime(mydata$time, "%Y-%m-%d %H:%M:%S", tz="GMT+1"))

[1] "2015-03-08 00:00:00 GMT" "2015-03-08 01:00:00 GMT" "2015-03-08 02:00:00 GMT"
[4] "2015-03-08 03:00:00 GMT"
Warning messages:
1: In strptime(mydata$time, "%Y-%m-%d %H:%M:%S", tz = "GMT+1") :
  unknown timezone 'GMT+1'
2: In as.POSIXct.POSIXlt(strptime(mydata$time, "%Y-%m-%d %H:%M:%S",  :
  unknown timezone 'GMT+1'
3: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'GMT+1'

如何使用表中的 utcOffset 信息将我的数据转换为 POSIXct?

【问题讨论】:

  • 我会选择"Etc/GMT+1"
  • 谢谢,as.POSIXct(strptime(mydata$time, "%Y-%m-%d %H:%M:%S", tz="Etc/GMT+1")) 在 Linux 和 Windows 上都可以工作。但是当我尝试使用我的 utcOffset 列中的值时:as.POSIXct(strptime(mydata$time, "%Y-%m-%d %H:%M:%S", tz=paste("Etc/GMT+", mydata$utcOffset, sep=""))) 我仍然收到 invalid 'tz' value 错误。
  • 如何将 utcOffset 添加到所有时间并将它们引用到 UTC? POSIXct 单位是秒,因此您可以添加:times.utc &lt;- times + utcOffsets*3600
  • 很好的建议。我试过了,它奏效了!在 as.POSIXct 函数中,我使用了tz="GMT",之后我添加了另一行以确保 R 知道添加了 utcOffset 的时间是 UTC:attr(times.utc, "tzone") &lt;- "GMT"
  • 做粘贴方法时,使用mapply/Map - as.POSIXct(mapply(as.POSIXct, mydata$time, paste0("Etc/GMT+", mydata$utcOffset)), tz="UTC",origin="1970-01-01")

标签: r timezone posixct timezone-offset strptime


【解决方案1】:

感谢 oshun 的评论,我找到了问题的答案:

times <- c("2015-03-08 00:00:00", "2015-03-08 01:00:00", "2015-03-08 02:00:00", "2015-03-08 03:00:00")
utcOffsets <- c(2, 1, 1, 1)
mydata <- data.frame(time=times, utcOffset=utcOffsets)

# convert the times to POSIXct (use UTC as default timezone)
localTimes <- as.POSIXct(times, format="%Y-%m-%d %H:%M:%S", tz="GMT")
mydata$UTCTime <- localTimes + utcOffsets*3600

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 2022-06-27
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    相关资源
    最近更新 更多