How to convert date & time to numeric by using POSIXct and how to calculate the time?

360 views Asked by At

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

There are 2 answers

1
Ronak Shah On BEST ANSWER

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")
2
danlooo On

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)