Question

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("2014-02-12 17:00:00", tz = "EST")

I want to create a new variable timeL that is the local time. Any suggestions of how to do this with R?

Thanks!

Was it helpful?

Solution

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"

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top