【问题标题】:convert to local time zone using latitude and longitude?使用纬度和经度转换为本地时区?
【发布时间】:2014-06-18 07:45:42
【问题描述】:

我有一个包含以下信息的数据集:纬度、经度、美国东部标准时间。例如,对于一次观察

lat = 13
long = -2
time1 = as.POSIXlt("2014-02-12 17:00:00", tz = "EST")

我想创建一个新的变量 timeL,它是本地时间。有关如何使用 R 执行此操作的任何建议?

谢谢!

【问题讨论】:

    标签: r timezone


    【解决方案1】:

    另一种方法是将目标点坐标与全球时区的 shapefile 相交,然后将 EST 时间戳转换为每个空间点的本地时间。例如,世界时区的边界可从Timezone Boundary Builder (direct download) 获得。

    library(sf)
    
    ## example data
    dat = data.frame(lon = -2
                     , lat = 13
                     , time1 = as.POSIXlt("2014-02-12 17:00:00", tz = "EST"))
    
    ## convert to 'sf' object
    sdf = st_as_sf(dat, coords = c("lon", "lat"), crs = 4326)
    
    ## import timezones (after extraction) and intersect with spatial points
    tzs = st_read("timezones.geojson/combined.json", quiet = TRUE)
    sdf = st_join(sdf, tzs)
    
    ## convert timestamps to local time
    sdf$timeL = as.POSIXlt(sdf$time1, tz = as.character(sdf$tzid))
    sdf$timeL
    # [1] "2014-02-12 22:00:00 GMT"
    

    请注意,对应的时区Africa/Ouagadougou 是格林威治标准时间。

    【讨论】:

    • 除了完整的st_intersection,您还可以使用st_join(只需在代码中替换)来连接时区属性。对于此示例,这可能无关紧要,但 st_join 通常对于较大的数据集要快得多,并且对于多边形内的点查询会产生相同的结果。
    • 同意,感谢您指出这一点。另请参阅 GitHub 上的 Vectorize st_intersection 问题。
    【解决方案2】:
    lat = 13
    long = -2
    time1 <- as.POSIXct("2014-02-12 17:00:00", tz = "EST")
    # https://developers.google.com/maps/documentation/timezone/
    apiurl <- sprintf("https://maps.googleapis.com/maps/api/timezone/%s?location=%s,%s&timestamp=%d&sensor=%s", 
                      "xml", 
                      lat, 
                      long, 
                      as.numeric(time1), 
                      "false")
    library(XML)
    tz <- xmlParse(readLines(apiurl))[["string(//time_zone_id)"]]
    as.POSIXct(format(time1, tz=tz))
    # [1] "2014-02-12 22:00:00 CET"
    

    或者,按照@SymbolixAU 的建议,使用他们的googleway 包:

    res <- googleway::google_timezone(c(lat, long), time1, key = NULL)
    as.POSIXct(format(time1, tz=res$timeZoneId))
    # [1] "2014-02-12 22:00:00 CET"
    

    【讨论】:

    • 在我的googleway pacakge 中还有 API 包装器 google_timezone(),可以避免自己解析 XML。
    • lat = 114 我得到 tz = "",为什么?
    • @Claudia 你期望什么?
    • 嗨,我试过你的解决方案,但由于某种原因,输出是 GMT,即使我的坐标是 Lat - 3, Lon 160。我已经尝试了两种解决方案:time1 &lt;- as.POSIXct("2015-10-30 03:50:00", tz = "UTC")res &lt;- googleway::google_timezone(c(-3, 162), time1, key = NULL)@987654329 @
    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多