本文介绍了从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
希望这会有所帮助!
重要说明:
- 请参阅下面的SymbolixAU的评论.尽管从技术上讲您不需要一个,但根据 Google的要求,您应该请求一个API密钥,并在上面的
google_timezone()
函数中使用该密钥. - Google API有一定的使用限制.如果打算在较大的数据帧上执行此操作,请考虑仅对唯一的经度和纬度对进行分组,甚至可能将它们四舍五入为
x
个数字.然后,您可以将google_timezone()
应用于这些唯一的组合,然后将它们合并回原始的dataframe
.
- 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 applygoogle_timezone()
on these unique combinations, and later merge them back to the originaldataframe
.
这篇关于从UTC时间获取当地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!