简体   繁体   中英

Find difference between times in R

Help me to find difference between times.For eg: these are the date and time

2015-11-24 16:49:14
2014-12-02 16:52:43

Need the result in HH:MM:SS format using r.

As you need difference between only the time, ignoring the dates you can first extract the time using strptime

x <- strptime(substr(a, 12, 19), format="%H:%M:%S")
y <- strptime(substr(b, 12, 19), format="%H:%M:%S")

Then using the seconds_to_period function of lubridate package you can get the time difference and then format the output using sprintf

library(lubridate)
temp <- seconds_to_period(as.numeric(difftime(y, x, units = "secs")))
sprintf('%02d:%02d:%02d', hour(temp), minute(temp), second(temp)) 

# [1] "00:03:29"     

data

a <- as.POSIXct("2015-11-24 16:49:14") 
b <- as.POSIXct("2014-12-02 16:52:43")

Following code to get the difference

library(lubridate)
interval(ymd_hms("2015-11-2416:17:38"),ymd_hms("2015-11-24 14:19:44"))
span<-interval(as.POSIXct("2015-11-24 16:17:38"),
as.POSIXct("2015-11-24 14:19:44")) 
as.period(span)

Format of answer

> -1H -57M -54S

Also display the difference in year, month & date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM