简体   繁体   English

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

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

I am importing multiple Excel sheets to R using readxl . 我正在使用readxl将多个Excel工作表导入到R中。 Each of these sheets contains observations of transactions which include DateOfEvent and TimeOfEvent fields. 这些工作表每个都包含对事务的观察,其中包括DateOfEventTimeOfEvent字段。

When I import the time field, R converts it to a POSIXct object based on the date being from Excel Day 0 - ie 1899-12-31 0:0:0 当我导入时间字段时,R根据来自Excel Day 0的日期将其转换为POSIXct对象-即1899-12-31 0:0:0

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

With the data in a data frame, using a dplyr step to clean my data, how would I - 将数据放在数据帧中,使用dplyr步骤清理数据,我将如何-

  • Use lubridate to recode the date part of the variable using the DateOfEvent value? 使用lubridate使用DateOfEvent值重新编码变量的日期部分吗?
  • Keep the times but make them independent of date so that I can compare events occurring in time buckets across different days (ie drop the 1899 date but format the date so that I can perform cross day comparisons)? 保留时间,但使它们不受日期影响,以便我可以比较不同时段在时间段中发生的事件(即删除1899年的日期,但格式化日期以便我可以进行跨天比较)?

Use update() to change the year in time . 使用update()来改变一年的time
Use hms::as.hms() if you want to extract just the time object from time (this will convert to UTC): 如果只想从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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM