convert to local time zone using latitude and longitude?

后端 未结 2 783
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 04:25

I have a data set with the following information: latitude, longitude, EST time. For example, for one observation

lat = 13
long = -2
time1 = as.POSIXlt(\"201         


        
相关标签:
2条回答
  • 2020-12-18 04:43
    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"
    

    or, as suggested by @SymbolixAU, use their googleway package:

    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"
    
    0 讨论(0)
  • 2020-12-18 04:59

    An alternate approach is to intersect the target point coordinates with a shapefile of global time zones and subsequently convert the EST timestamps to the local time at each spatial point. For example, boundaries of the world's time zones are available from Timezone Boundary Builder (direct 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"
    

    Note that the corresponding time zone Africa/Ouagadougou is GMT.

    0 讨论(0)
提交回复
热议问题