【问题标题】:Get the local time from a UTC time从 UTC 时间获取本地时间
【发布时间】:2018-07-02 16:09:54
【问题描述】:

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

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 转换为当地时间?

【问题讨论】:

    标签: r time timezone data.table latitude-longitude


    【解决方案1】:

    我找到了将经度和纬度转换为时区的好答案here,因此我们可以将这种方法应用于您的用例。

    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's requirements,您应该请求一个 API 密钥并在上面的 google_timezone() 函数中使用它。
    • Google API 有一定的使用限制。如果您打算在大型数据帧上执行此操作,请考虑仅对唯一的经度和纬度对进行子集化,甚至可能将它们四舍五入为 x 数字。然后,您可以将google_timezone() 应用于这些独特的组合,然后将它们合并回原来的dataframe

    【讨论】:

    • 不错的解决方案。这个SO question 也可能有用
    • 哇,这是一个广泛的答案。感谢分享。
    • 虽然很高兴看到 googleway 被使用,但请记住,根据 Google's requirements,您应该使用 API 密钥(即使从技术上讲您不需要一)。
    • @SymbolixAU 感谢您的评论(和一个很棒的包),我已将其添加到答案中。
    猜你喜欢
    • 2012-10-08
    • 2014-09-15
    • 1970-01-01
    • 2011-11-24
    • 2014-03-03
    • 2012-09-23
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多