diff_times
computes the difference between two times
(i.e., from some from_time
to some to_time
)
in human measurement units (periods).
diff_times(from_time, to_time = Sys.time(), unit = "days", as_character = TRUE)
A character vector or data frame (with times, sign, and numeric columns for units).
From time (required, scalar or vector, as "POSIXct"). Origin time, assumed to be of class "POSIXct", and coerced into "POSIXct" when of class "Date" or "POSIXlt.
To time (optional, scalar or vector, as "POSIXct").
Default: to_time = Sys.time()
.
Maximum time, assumed to be of class "POSIXct",
and coerced into "POSIXct" when of class "Date" or "POSIXlt".
Largest measurement unit for representing results.
Units represent human time periods, rather than
chronological time differences.
Default: unit = "days"
for completed days, hours, minutes, and seconds.
Options available:
unit = "years"
: completed years, months, and days (default)
unit = "months"
: completed months, and days
unit = "days"
: completed days
unit = "hours"
: completed hours
unit = "minutes"
: completed minutes
unit = "seconds"
: completed seconds
Units may be abbreviated.
Boolean: Return output as character?
Default: as_character = TRUE
.
If as_character = FALSE
, results are returned
as columns of a data frame
and include from_date
and to_date
.
diff_times
answers questions like
"How much time has elapsed between two dates?"
or "How old are you?" in human time periods
of (full) years, months, and days.
Key characteristics:
If to_time
or from_time
are not "POSIXct" objects,
diff_times
aims to coerce them into "POSIXct" objects.
If to_time
is missing (i.e., NA
),
to_time
is set to the current time (i.e., Sys.time()
).
If to_time
is specified, any intermittent missing values
(i.e., NA
) are set to the current time (i.e., Sys.time()
).
If to_time
precedes from_time
(i.e., from_time > to_time
)
computations are performed on swapped times and the result is marked
as negative (by a character "-"
) in the output.
If the lengths of from_time
and to_time
differ,
the shorter vector is recycled to the length of the longer one.
By default, diff_times
provides output as (signed) character strings.
For numeric outputs, use as_character = FALSE
.
diff_dates
for date differences;
time spans (an interval
as.period
) in the lubridate package.
Other date and time functions:
change_time()
,
change_tz()
,
cur_date()
,
cur_time()
,
days_in_month()
,
diff_dates()
,
diff_tz()
,
is_leap_year()
,
what_date()
,
what_month()
,
what_time()
,
what_wday()
,
what_week()
,
what_year()
,
zodiac()
t1 <- as.POSIXct("1969-07-13 13:53 CET") # (before UNIX epoch)
diff_times(t1, unit = "years", as_character = TRUE)
diff_times(t1, unit = "secs", as_character = TRUE)
Run the code above in your browser using DataLab