Describe a time as the elapsed time between two date or datetime columns.
duration(
start,
end,
*,
unit="days",
)
Study exports often record calendar dates (enrollment, last contact, death) rather than durations. duration() names the two columns and the time unit, and Greenwood computes the difference when it reads the data. Pass the result as the time (or time2) argument of an Outcome constructor. Inside a formula, write duration(enroll, exit, unit="years") instead.
Parameters
start: str
-
The column holding the origin, such as an enrollment date.
end: str
-
The column holding the exit, such as the date of the event or of last contact.
unit: str = "days"
-
The time unit:
"days" (the default), "weeks", "months", "years", "hours", "minutes", or "seconds". Months and years use average lengths (30.4375 and 365.25 days).
Returns
Duration
-
A frozen Duration spec holding the two column names and the unit. It is computed when the data is read, and it prints as the call that made it, such as
duration(start='enroll', end='exit', unit='days'). The Duration class is exported for type annotations.
Examples
Compute follow-up time in years from two date columns:
import greenwood as gw
import polars as pl
from datetime import date
study = pl.DataFrame({
"enroll": [date(2021, 3, 1), date(2021, 3, 15), date(2021, 4, 1)],
"exit": [date(2022, 1, 10), date(2021, 9, 22), date(2023, 1, 1)],
"outcome": ["died", "censored", "died"],
})
# The time is the gap between the two dates, in years
gw.Outcome.surv(
time=gw.duration(start="enroll", end="exit", unit="years"),
event="outcome == 'died'",
).bind(study)
Surv(type=right, n=3, events=2)
The same response written as a formula, fitted with data=:
gw.KaplanMeier().fit(
"Surv(duration(enroll, exit, unit='years'), outcome == 'died')", data=study
)
KaplanMeier (Kaplan-Meier survival estimate)
n events median 0.95LCL 0.95UCL
all 3 2 0.8624 0.8624 NA