years()#
relationalai.std.dates
#years(n: int|Producer) -> Expression
Creates a period of n
years.
Negative values are supported.
If n
is a Producer
object, then years()
also acts as a filter and removes non-integer values from the producer.
Must be called in a rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
n | Producer or Python int | The number of years. |
Returns#
An Expression
object.
Example#
Use years()
to create a period of n
years.
You can add and subtract time periods from date or datetime values using the +
and -
operators:
#import relationalai as rai
from relationalai.std import alias, dates
# =====
# SETUP
# =====
model = rai.Model("MyModel")
Event = model.Type("Event")
with model.rule():
Event.add(id=1).set(start=dates.date(2021, 1, 1), duration_years=1)
Event.add(id=2).set(start=dates.datetime(2021, 2, 1, 9, 30), duration_years=2)
Event.add(id=3).set(start=dates.date(2021, 3, 1), duration_years=-1)
Event.add(id=4).set(start=dates.date(2021, 4, 1), duration_years="invalid")
# =======
# EXAMPLE
# =======
with model.rule():
event = Event()
# years() filters out any events with invalid duration_years, so the following
# only sets the end property for Events 1, 2, and 3.
event.set(end=event.start + dates.years(event.duration_years))
# Since Event 3 is filtered out above, the following only sets the
# has_valid_duration property for Events 1, 2, and 3.
event.set(has_valid_duration=True)
with model.query() as select:
event = Event()
response = select(event.id, event.end, event.has_valid_duration)
print(response.results)
# id end has_valid_duration
# 0 1 2022-01-01 00:00:00 True
# 1 2 2023-02-01 09:30:00 True
# 2 3 2020-03-01 00:00:00 True
# 3 4 NaT NaN
Note that years()
does not produce an integer value.
In particular, you can not do arithmetic with years()
and numeric values:
#with model.query() as select:
days = dates.years(2) * 365
response = select(days)
# Returns an empty result set because `years(2) * 365` is not a valid expression.
print(response.results)
# Empty DataFrame
# Columns: []
# Index: []