Get the local time from a UTC time

懵懂的女人 提交于 2021-01-27 23:46:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48408507/get-the-local-time-from-a-utc-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!