Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

r - How to calculate hours between two as.characters with the format "dd-mm-yyyy hh:mm"

I have u with time1 and time2 both listed with the format dd-mm-yyyy hh:mm. I would like to produce a new covariate containing the hours between u$time1 and u$time2.

They are listed as as.character

str(u)
'data.frame':   5765 obs. of  2 variables:
 $ time1: chr  "30-01-2020 07:20" "25-04-2019 15:05" "11-01-2019 22:01" "11-01-2019 22:01" ...
 $ time2: chr  "14-02-2020 15:34" "27-04-2019 10:56" "12-01-2019 00:42" "23-01-2019 10:08" ...

The expected output

>  head(u)
             time1            time2                            new
1 30-01-2020 07:20 14-02-2020 15:34  hours between time1 and time2
2 25-04-2019 15:05 27-04-2019 10:56  hours between time1 and time2
3 11-01-2019 22:01 12-01-2019 00:42  hours between time1 and time2
4 11-01-2019 22:01 23-01-2019 10:08  hours between time1 and time2

I would prefer if the hours had one decimal point, and a solution with dplyr or lubridate would be preferred.

u <- structure(list(time1 = c("30-01-2020 07:20", "25-04-2019 15:05", 
"11-01-2019 22:01", "11-01-2019 22:01", "17-04-2018 07:55"), 
    time2 = c("14-02-2020 15:34", "27-04-2019 10:56", "12-01-2019 00:42", 
    "23-01-2019 10:08", "20-04-2018 11:04")), row.names = c(NA, 
5L), class = "data.frame")
question from:https://stackoverflow.com/questions/65927120/how-to-calculate-hours-between-two-as-characters-with-the-format-dd-mm-yyyy-hh

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We can use difftime after converting to POSIXct

with(u, difftime(as.POSIXct(time1, format = '%d-%m-%Y %H:%M'), 
       as.POSIXct(time2, format = '%d-%m-%Y %H:%M'), units = 'hour'))

Or as @r2evans mentioned in the comments, the lubridate option is

library(lubridate)
as.numeric(dmy_hm(u$time1) - dmy_hm(u$time2), units = "hours")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...