You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中向POSIXct函数的tz参数传入字符串向量问题

Convert GMT Timestamps to Per-Element Local Timezones

Hey there! I totally get the frustration here—trying to map a vector of GMT timestamps to their unique corresponding timezones doesn't work with straightforward POSIXct() or with_tz() calls because those functions are designed to accept a single timezone string, not a vector of them. Let's fix this with element-wise processing.

Why Your Initial Attempts Failed

First, a quick clarification: Both POSIXct(tz = ...) and lubridate::with_tz(tz = ...) expect a single timezone value (like "America/New_York"). When you pass a vector of timezones, they'll either ignore all but the first value or throw a warning—they can't natively map each timestamp to its own timezone.

Solution 1: Base R with mapply()

If you prefer sticking to base R, mapply() is perfect for pairing elements from your two vectors and processing them one by one:

# Example sample data (replace with your actual vectors)
GMTDteTmeStamp <- as.POSIXct(c("2024-05-20 12:00:00", "2024-05-20 13:00:00"), tz = "GMT")
TZ <- c("America/New_York", "Europe/London")

# Use mapply to convert each timestamp with its matching timezone
local_time_list <- mapply(
  function(gmt_ts, tz) lubridate::with_tz(gmt_ts, tz = tz),
  GMTDteTmeStamp,
  TZ,
  SIMPLIFY = FALSE
)

# Convert the resulting list to a POSIXct vector if needed
local_time_vec <- do.call(c, local_time_list)

# Check the output
local_time_vec
#> [1] "2024-05-20 08:00:00 EDT" "2024-05-20 14:00:00 BST"

Solution 2: Tidyverse with purrr::map2()

If you're working with a data frame (which is common for paired data), the tidyverse approach is clean and readable:

library(tidyverse)
library(lubridate)

# Example data frame (replace with your data)
time_data <- tibble(
  GMTDteTmeStamp = as.POSIXct(c("2024-05-20 12:00:00", "2024-05-20 13:00:00"), tz = "GMT"),
  TZ = c("America/New_York", "Europe/London")
)

# Add a column of converted local times
time_data <- time_data %>%
  mutate(local_time = map2(GMTDteTmeStamp, TZ, ~with_tz(.x, tz = .y))) %>%
  unnest(local_time)

# View the result
time_data
#> # A tibble: 2 × 3
#>   GMTDteTmeStamp      TZ                local_time         
#>   <dttm>              <chr>             <dttm>             
#> 1 2024-05-20 12:00:00 America/New_York 2024-05-20 08:00:00
#> 2 2024-05-20 13:00:00 Europe/London    2024-05-20 14:00:00

Key Notes

  • Both methods handle daylight saving time automatically, so you don't need to adjust for that manually.
  • Make sure your TZ vector uses valid timezone names (like those from OlsonNames()—you mentioned manual single-timezone calls work, so your values are already good here).

内容的提问来源于stack exchange,提问作者Michael Byars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:06:10