简体   繁体   中英

Get the local time from a UTC time

Let's say I have a data set with the date, latitude, and longitude.

dt = data.table(date = c("2017-10-24 05:01:05",
                         "2017-10-24 05:01:57", 
                         "2017-10-24 05:02:54"),
                lat = c(-6.2704925537109375,
                        -6.2704925537109375,
                        -6.2704925537109375),
                long = c(106.5803680419922, 
                         106.5803680419922,
                         106.5803680419922))

The time is UTC. Is it possible to transfer that UTC to the local time using the lat and long?

I found a good answer on converting longitude and latitude to timezones here , so here is how we can apply that method to your use case.

library(data.table)
library(googleway)
library(lubridate)
dt = data.table(date = c("2017-10-24 05:01:05",
                         "2017-10-24 05:01:57", 
                         "2017-10-24 05:02:54"),
                lat = c(-6.2704925537109375,
                        -6.2704925537109375,
                        -6.2704925537109375),
                long = c(106.5803680419922, 
                         106.5803680419922,
                         106.5803680419922))

dt$date <- with_tz(as.POSIXct(dt$date), "UTC")

convert_time <- function(lat,lon,time_x)
{
  my_time <- google_timezone(c(lat, lon), key = NULL)
  as.POSIXct(format(time_x, tz=my_time$timeZoneId)) 
}

dt[,time_conv:=convert_time(lat,long,date),by=1:nrow(dt)]

Output:

                  date       lat     long           time_conv
1: 2017-10-24 03:01:05 -6.270493 106.5804 2017-10-24 10:01:05
2: 2017-10-24 03:01:57 -6.270493 106.5804 2017-10-24 10:01:57
3: 2017-10-24 03:02:54 -6.270493 106.5804 2017-10-24 10:02:54

Hope this helps!


Important notes:

  • See SymbolixAU's comment below. Although technically you do not need one, as per Google's requirements you should request an API key and use that in the google_timezone() function above.
  • The Google API has certain usage limits. If you plan to do this on a large dataframe, consider subsetting only unique longitude and latitude pairs and possibly even rounding them to x digits. You can then apply google_timezone() on these unique combinations, and later merge them back to the original dataframe .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM