Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R difftime() Function - Computing Time Differences

R difftime() Function - Computing Time Differences

R Language Examples R Language Examples

The R difftime() function is used to compute the difference between two dates/times.

difftime() can specify the unit of the returned time difference, such as days, hours, minutes, and so on.

The syntax of the difftime() function is as follows:

difftime(time1, time2, units = c("auto", "secs", "mins", "hours", "days", "weeks"))

Parameter Description:

Example

Two dates

start_date

<-

as.Date

(

"2026-01-01"

)

end_date

<-

as.Date

(

"2026-05-11"

)

Compute the difference (in days by default)

diff_days

<-

difftime

(

end_date, start_date

)

print

(

paste

(

"Days Difference:"

, diff_days

)

)

Specify the unit as weeks

diff_weeks

<-

difftime

(

end_date, start_date,

units

=

"weeks"

)

print

(

paste

(

"Week difference:"

,

round

(

diff_weeks,

1

)

)

)

Date Comparison

dates

<-

as.Date

(

c

(

"2025-06-15"

,

"2026-01-01"

,

                   

"2026-05-11"

,

"2026-12-31"

)

)

reference

<-

as.Date

(

"2026-05-11"

)

diffs

<-

difftime

(

dates, reference,

units

=

"days"

)

print

(

"Day difference between each date and today:"

)

print

(

diffs

)

The output of the code above is:

[1] "相差天数: 130"

[1] "相差周数: 18.6"

[1] "各日期与今天的天数差:"

Time differences in days

[1] -330 -130    0  234

R Language Examples R Language Examples