将大型数据集中的列从 UTC 转换为 R 中的 PST

Convert a column within a large dataset from UTC to PST in R

我有一个大型数据集 df,我想将日期列转换为 PST。当前为 UTC 时间。

   Date                        ID

   1/7/2020 1:35:08 AM         A

我想将日期列从 UTC 转换为 PST,同时保留其他列。

   Date                        ID

   1/7/2020 5:35:08 PM         A

这是输出:

  structure(list(Date = structure(1L, .Label = "1/7/2020 1:35:08 AM", class = "factor"), 
  ID = structure(1L, .Label = "A", class = "factor")), class = "data.frame", row.names = c(NA, 
 -1L))

这是我试过的:

  library(lubridate)
  newdata <- as.POSIXct(Sys.Date())

但是,我不确定是否需要添加格式以及还需要添加哪些其他代码。

使用 lubridate 你可以做到:

library(lubridate)
df$Date <- mdy_hms(df$Date)
df$Date <- with_tz(df$Date, tzone = "America/Los_Angeles")
df

#                 Date ID
#1 2020-01-06 17:35:08  A

或在基数 R 中:

df$Date <- as.POSIXct(df$Date, format = "%m/%d/%Y %I:%M:%S %p", tz = "UTC")
attributes(df$Date)$tzone <- "America/Los_Angeles"