Harshit Chepe
Harshit Chepe

Reputation: 23

How do I subtract Date column given as a character in R?

Store_Entry_Time and Store_Exit_Time are character classes

I want to add a column which is a subtraction of Store_Entry_Time from Store_Exit_Time. For example the result for row 1 should be (2014-12-02 18:49:05.402863 - 2014-12-02 16:56:32.394052) = 1 hour 53 minutes approximately.( I want this result in just hours). I entered class(Store_Entry_Time) and it says "character". How do I obtain the subtracting and put it into new column as "Time Spent"?

Upvotes: 0

Views: 852

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

For a base R option here, we can try using as.POSIXct:

df$Time_Spent <- as.numeric(as.POSIXct(df$Store_Exit_Time) -
                            as.POSIXct(df$Store_Entry_Time)

The above column would give the difference in time, measured in hours.

Example:

Store_Exit_Time <- "2014-12-02 18:49:05.402863"
Store_Entry_Time <- "2014-12-02 16:56:32.394052"
Time_Spent <- as.numeric(as.POSIXct(Store_Exit_Time) - as.POSIXct(Store_Entry_Time))
Time_Spent

[1] 1.875836

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388797

You can use ymd_hms from lubridate to convert the column into POSIXct format and then use difftime to caluclate the difference in time.

library(dplyr)

df <- df %>%
         mutate(across(c(Store_Entry_Time, Store_Exit_Time), lubridate::ymd_hms),
                Time_Spent = as.numeric(difftime(Store_Exit_Time, 
                               Store_Entry_Time, units = 'hours')))

Upvotes: 1

Related Questions