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



我有一个大数据集df,我想将Date列转换为PST。目前是UTC时间。

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

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

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

这是dput:

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"

最新更新