Calculate time difference in R with difftime function

Difference between two times is calculated in R using difftime function (). Difference between two dates are also can be calculated using difftime function in R.

Syntax of difftime function in R:

difftime(time1, time2, tz, units = c(“auto”, “secs”, “mins”, “hours”,”days”, “weeks”))

 

time1 later time or recent time.
time 2 earlier time
Tz timezone
Units units in which result should be calculated – units can be seconds, minutes,hours,days,weeks

 

Example of time difference- difftime function in R :

# difftime() function in R: calculate the time difference between two times

recent_time <- "2017-04-06"
earlier_time <- "2011-05-01 11:00:00"
difftime(recent_time,earlier_time)

by default the time difference between two times are calculated in days, so the output will be

Time difference of 2166.542 days

 

 

R Difference in time with time zone:

#difference in time with time zone :difftime function in R
difftime(recent_time,earlier_time,tz="EST")

time zone (tz) is an optional argument, it can be “EST” or “GMT” etc

output:
Time difference of 2166.542 days

 

 

R Difference in time with time zone and units in seconds:

#difference in time with time zone and units in seconds

difftime(recent_time,earlier_time,tz="GMT",units="secs")
output:
Time difference of 187189200 secs

 

R Difference in time with time zone and units in minutes:

#time difference in R:difference in time with time zone and units in minutes

difftime(recent_time,earlier_time,tz="GMT",units="mins")
output:
Time difference of 3119820 mins

 

 

R Difference in time with time zone and units in hours:

# time difference in R:difference in time with time zone and units in hours

difftime(recent_time,earlier_time,tz="GMT",units="hours")
output:
Time difference of 51997 hours

 

 

R Difference in time with time zone and units in days:

#difference in time with time zone and units in days

difftime(recent_time,earlier_time,tz="GMT",units="days")
output:
Time difference of 2166.542 days

 

 

 

R Difference in time with time zone and units in weeks:

#difference in time with time zone and units in weeks

difftime(recent_time,earlier_time,tz="GMT",units="weeks")
output:
Time difference of 309.506 weeks

 

previous small r difference in time                                                                                                           next small r difference in time

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts