R difftime() Function - Calculate Time Difference

R 语言实例R Language Example

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

difftime() allows you to specify the time unit of the returned value, such as days, hours, minutes, etc.

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

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

Parameter description:

  • time1, time2Date-time object.

  • unitsThe time unit for the returned difference.

Example

# Two dates
start_date <- as.Date("2026-01-01")
end_date <- as.Date("2026-05-11")

# Calculate the difference (default days)
diff_days <- difftime(end_date, start_date)
print(paste("Difference in days:", diff_days))

# Specify the unit as weeks
diff_weeks <- difftime(end_date, start_date, units = "weeks")
print(paste("Difference in weeks:", 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("Difference in days between each date and today:")
print(diffs)

Executing the above code produces the following output:

[1] "相差天数: 130"
[1] "相差周数: 18.6"
[1] "各日期与今天的天数差:"
Time differences in days
[1] -330 -130    0  234

R 语言实例R Language Example

Other Extensions