使用纬度和经度转换为本地时区?

时间:2014-05-01 18:45:32

标签: r timezone

我有一个包含以下信息的数据集:纬度,经度,EST时间。例如,一次观察

lat = 13
long = -2
time1 = as.POSIXlt("2014-02-12 17:00:00", tz = "EST")

我想创建一个新的变量timeL,即本地时间。有关如何使用R?

的任何建议

谢谢!

2 个答案:

答案 0 :(得分:13)

lat = 13
long = -2
time1 <- as.POSIXct("2014-02-12 17:00:00", tz = "EST")
# https://developers.google.com/maps/documentation/timezone/
apiurl <- sprintf("https://maps.googleapis.com/maps/api/timezone/%s?location=%s,%s&timestamp=%d&sensor=%s", 
                  "xml", 
                  lat, 
                  long, 
                  as.numeric(time1), 
                  "false")
library(XML)
tz <- xmlParse(readLines(apiurl))[["string(//time_zone_id)"]]
as.POSIXct(format(time1, tz=tz))
# [1] "2014-02-12 22:00:00 CET"

或者,正如@SymbolixAU所建议的那样,使用他们的googleway包:

res <- googleway::google_timezone(c(lat, long), time1, key = NULL)
as.POSIXct(format(time1, tz=res$timeZoneId))
# [1] "2014-02-12 22:00:00 CET"

答案 1 :(得分:3)

另一种方法是将目标点坐标与全局时区的shapefile相交,然后将EST时间戳转换为每个空间点的本地时间。例如,世界时区的边界可从Timezone Boundary Builderdirect download)获得。

library(sf)

## example data
dat = data.frame(lon = -2
                 , lat = 13
                 , time1 = as.POSIXlt("2014-02-12 17:00:00", tz = "EST"))

## convert to 'sf' object
sdf = st_as_sf(dat, coords = c("lon", "lat"), crs = 4326)

## import timezones (after extraction) and intersect with spatial points
tzs = st_read("timezones.geojson/combined.json", quiet = TRUE)
sdf = st_join(sdf, tzs)

## convert timestamps to local time
sdf$timeL = as.POSIXlt(sdf$time1, tz = as.character(sdf$tzid))
sdf$timeL
# [1] "2014-02-12 22:00:00 GMT"

请注意,相应的时区Africa/Ouagadougou是GMT。