简体   繁体   中英

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

I am importing multiple Excel sheets to R using readxl . Each of these sheets contains observations of transactions which include DateOfEvent and TimeOfEvent fields.

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

eg 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 -

  • Use lubridate to recode the date part of the variable using the DateOfEvent value?
  • 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)?

Use update() to change the year in time .
Use hms::as.hms() if you want to extract just the time object from time (this will convert to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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