Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

r - convert to local time zone using latitude and longitude?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...