如何转换GMT + 4时区到UTC

时间:2017-07-02 14:53:30

标签: r datetime utc

我在Atlantic Daylight Time(GMT + 4)中有一个日期时间列,并希望使用以下代码转换为UTC,但我无法找到正确的tzone以使代码生效(它无法识别ADT或GMT + 4)。请允许有人提供帮助,因为我正在围绕圈子和tzone的帮助页面没有提供解决方案。

示例数据:

> dput(df)
structure(list(Date = c("05/04/17", "05/04/17", "05/04/17", "05/04/17", 
"05/04/17", "05/04/17", "05/04/17"), Time = c(" 12:10:26", " 12:11:01", 
" 12:11:38", " 12:12:13", " 12:12:48", " 12:13:24", " 12:13:58"
)), .Names = c("Date", "Time"), class = "data.frame", row.names = c(NA, 
-7L))

> df
      Date      Time
1 05/04/17  12:10:26
2 05/04/17  12:11:01
3 05/04/17  12:11:38
4 05/04/17  12:12:13
5 05/04/17  12:12:48
6 05/04/17  12:13:24
7 05/04/17  12:13:58

#Change system time to Atlantic Daylight Time (GMT+4)
  Sys.setenv(TZ = "ADT") 
  Sys.time()

#Combine date and time columns and convert into POSIXct object
  df$datetime_ADT = paste(df$Date,df$Time)
  df$datetime_ADT = dmy_hms(df$datetime_ADT)
  str(df$datetime_ADT)

  #create new column for UTC datetimes
  df$datetime_utc = df$datetime_ADT
  #transform ADT time into UTC time
  attr(df$datetime_utc, "tzone") = "UTC"
  #check timezone change worked!
  df$datetime_utc[1]
  df$datetime_ADT[1]

  #change system timezone back to default
  Sys.setenv(TZ = "") 

1 个答案:

答案 0 :(得分:1)

AST实际上是UTC-4,ADT是UTC-3(Wikipedia)。如果要直接转换,可以在读取时间时指定偏移量并将时区设置为UTC:

as.POSIXct(paste(df$Date, df$Time, '-0300'), format = '%d/%m/%y %T %z', tz = 'UTC')
#> [1] "2017-04-05 15:10:26 UTC" "2017-04-05 15:11:01 UTC"
#> [3] "2017-04-05 15:11:38 UTC" "2017-04-05 15:12:13 UTC"
#> [5] "2017-04-05 15:12:48 UTC" "2017-04-05 15:13:24 UTC"
#> [7] "2017-04-05 15:13:58 UTC"

或者更健壮,在ADT中从OlsonNames()选择一个地点并设置属性:

x <- as.POSIXct(paste(df$Date, df$Time), format = '%d/%m/%y %T', tz = 'America/Halifax')
attr(x, 'tzone') <- 'UTC'
x
#> [1] "2017-04-05 15:10:26 UTC" "2017-04-05 15:11:01 UTC"
#> [3] "2017-04-05 15:11:38 UTC" "2017-04-05 15:12:13 UTC"
#> [5] "2017-04-05 15:12:48 UTC" "2017-04-05 15:13:24 UTC"
#> [7] "2017-04-05 15:13:58 UTC"

或在dplyr with lubridate,

library(dplyr)
library(lubridate)

df %>% transmute(datetime = dmy_hms(paste(Date, Time), tz = 'America/Halifax'), 
                 datetime = with_tz(datetime, 'UTC'))
#>              datetime
#> 1 2017-04-05 15:10:26
#> 2 2017-04-05 15:11:01
#> 3 2017-04-05 15:11:38
#> 4 2017-04-05 15:12:13
#> 5 2017-04-05 15:12:48
#> 6 2017-04-05 15:13:24
#> 7 2017-04-05 15:13:58