问题
I have Log data, it records the Start datetime and end datetime stamp.
Data from the log file look as below Preapred data in excel
Start_Date1 Start_Time1 Start_Millisecond1 Start_Date2 Start_Time2 Start_Millisecond2
29-11-2015 18:25:04 671 29-11-2015 18:40:05 275
29-11-2015 18:25:03 836 29-11-2015 18:40:04 333
10-11-2015 02:41:57 286 10-11-2015 02:51:52 690
When i load the data into R using Rstudio. The class of data looks as below.
Data Loaded and Its data type
I am using below line of code to convert date to POSIXlt.
nov$Start.Date1<-as.POSIXlt(as.character(nov$Start.Date1), format="%d-%m-%Y")
nov <-read.csv(file = '././data/Data For R Nov CBEFF log.csv',header = TRUE,na.strings = FALSE,stringsAsFactors = FALSE)
str(nov$Start.Time1)
nov$Start.Date1<-as.POSIXlt(as.character(nov$Start.Date1), format="%d-%m-%Y")
nov$Start.Time1<-as.POSIXlt(as.character(nov$Start.Time1), format="%H:%M:%S") nov$Start.Time1<-format(nov$Start.Time1, format="%H:%M:%S")
nov$Start.Date2<-as.POSIXlt(as.character(nov$Start.Date2), format="%d-%m-%Y")
nov$Start.Time2<-as.POSIXlt(as.character(nov$Start.Time2), format="%H:%M:%S") nov$Start.Time2<-format(nov$Start.Time2, format="%H:%M:%S")
**
> I want to caluclate time taken to complete that is > StartTime2-StartTime1
**
StartTime1 and StartTime2 are now in chr data type.
回答1:
This should do the trick. If you had posted the data (reproducible example), I could check the code. This way it might have some typos in it.
nov<-read.delim("sample.csv", sep=";", dec=".")
nov$start1<-as.POSIXlt(paste(nov$Start_Date1,nov$Start_Time1 ,sep=" "), format="%d-%m-%Y %H:%M:%S")
nov$start2<-as.POSIXlt(paste(nov$Start_Date2,nov$Start_Time2 ,sep=" "), format="%d-%m-%Y %H:%M:%S")
nov$timediff<-as.numeric(difftime(nov$start2,nov$start1, unit="secs"))*1000+(nov$Start.Milisecond2-nov$Start.Milisecond1)
This gives you the time in miliseconds
EDIT Verified with sample data. The variable names have changed from "Start.Date1" to "Start_Date1"
来源:https://stackoverflow.com/questions/35624659/how-to-find-the-difference-of-time-time-taken-to-process-a-file-in-r