本文介绍了从UTC时间获取当地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含日期,纬度和经度的数据集.

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))

时间是UTC.是否可以使用时长将UTC转换为当地时间?

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)]

输出:

                  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

希望这会有所帮助!

重要说明:

  • 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.

这篇关于从UTC时间获取当地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:33