-2

Hi Friends Both these columns(starttime/stoptime) are in Character class ,how could I convert to numeric(POSIXct) to find the time consumption ,Thank you

starttime
12/31/2015 23:48
12/31/2015 23:47
12/31/2015 23:37
12/31/2015 23:37

stoptime
12/31/2015 23:51
12/31/2015 23:53
12/31/2015 23:43
1/1/2016 0:02

2 Answers2

1

The function parse_date_time from the lubridate package is a clean way to deal with time. Here is how to do it:

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
tribble(
  ~starttime, ~stoptime,
  "12/31/2015 23:48", "12/31/2015 23:51",
  "12/31/2015 23:47", "12/31/2015 23:53"
) %>%
  mutate(
    starttime = starttime %>% parse_date_time("%m/%d/%y %H:%M"),
    stoptime = stoptime %>% parse_date_time("%m/%d/%y %H:%M"),
    duration = stoptime - starttime
  )
#> # A tibble: 2 x 3
#>   starttime           stoptime            duration
#>   <dttm>              <dttm>              <drtn>  
#> 1 2015-12-31 23:48:00 2015-12-31 23:51:00 3 mins  
#> 2 2015-12-31 23:47:00 2015-12-31 23:53:00 6 mins

Created on 2021-09-09 by the reprex package (v2.0.0)

danlooo
  • 10,067
  • 2
  • 8
  • 22
  • Thank you ,but I have one million rows in each start and stop time ,so How could I use tribble – Robin Anthony Joseph Sep 10 '21 at 08:43
  • You probably have the rows stored in a file. `tribble` is just to give an example dataset for demonstration purposes. Replace this command with e.g. `read_csv` or `read_excel` depending on your file – danlooo Sep 10 '21 at 08:47
0

Additionally, you can also use mdy_hm function from lubridate -

library(dplyr)
library(lubridate)

df <- df %>% mutate(across(c(starttime, stoptime), mdy_hm))

In base R, you can use as.POSIXct

df[1:2] <- lapply(df[1:2], as.POSIXct, format = "%m/%d/%Y %H:%M")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213