how to calculate the difference in minutes between 2 times
Example:-
Start_time end_time
17:15:49 17:22:44
additionally the type of these variable is (unknown) how to convert it to time?
how to calculate the difference in minutes between 2 times
Example:-
Start_time end_time
17:15:49 17:22:44
additionally the type of these variable is (unknown) how to convert it to time?
Hello @Marwa_Abd_Elfattah ,
dates and times I allways find a bit tricky and therefore I like to use the R package lubridate
.
If you don't know the type it is probably character but if the dates comes from a spreadsheet they could be numeric. For now assuming they are character and already given in a data.frame
you could do this.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
df <- data.frame(
stringsAsFactors = F,
start = c("17:15:49","17:22:44"),
end = c("17:22:44","18:00:00")
)
df
#> start end
#> 1 17:15:49 17:22:44
#> 2 17:22:44 18:00:00
df %>%
mutate(start = lubridate::parse_date_time(start,"%H:%M:%S"),
end = lubridate::parse_date_time(end,"%H:%M:%S"),
dif = end - start)
#> start end dif
#> 1 0000-01-01 17:15:49 0000-01-01 17:22:44 6.916667 mins
#> 2 0000-01-01 17:22:44 0000-01-01 18:00:00 37.266667 mins
Created on 2021-09-16 by the reprex package (v2.0.0)
You see that the characters are converted to date-time type (with the same date !!) and then the difference is taken. I hope this matches your problem and otherwise just ask here.
first thanks for the reply. But it didn't work and converted all the started_ and ended _at values to NA. and the following error is appeared.
Warning messages:
1: Problem with mutate()
column started_at
.
i started_at = parse_date_time(started_at, "%H:%M:%S")
.
i All formats failed to parse. No formats found.
2: Problem with mutate()
column ended_at
.
i ended_at = parse_date_time(ended_at, "%H:%M:%S")
.
i All formats failed to parse. No formats found.
If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.