如何操作从 Excel 导入到 R 中的日期时间变量

How do I manipulate a datetime variable imported from Excel into R

我正在使用 readxl 将多张 Excel 工作表导入 R。这些工作表中的每一个都包含对交易的观察,其中包括 DateOfEventTimeOfEvent 字段。

当我导入时间字段时,R 根据 Excel 第 0 天的日期将其转换为 POSIXct 对象 - 即 1899-12-31 0:0:0

例如dat <- data.frame(date=Sys.Date()+0:1, time=as.POSIXct(c(10,11), origin="1899-12-31"))

使用数据框中的数据,使用 dplyr 步骤来清理我的数据,我将如何 -

使用 update() 更改 time 中的年份。
如果您只想从 time 中提取时间对象,请使用 hms::as.hms()(这将转换为 UTC):

library(tidyverse)

dat %>% 
  mutate(time = update(time, 
                       year = year(date), 
                       month = month(date), 
                       day = day(date)),
         hms = hms::as.hms(time))

        date                time      hms
1 2018-06-02 2018-06-02 16:00:10 23:00:10
2 2018-06-03 2018-06-03 16:00:11 23:00:11