date_subtract()#
relationalai.std.dates
#date_subtract(
date: date | datetime | Producer,
period: Producer
) -> Expression
Subtracts a time period from a Date
or DateTime
value.
Must be called in a rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
date | date or datetime or Producer | The Date or DateTime value from which to subtract the time period. |
period | Producer | The time period to subtract (e.g., day() , week() , month() , year() ). |
Returns#
An Expression
that produces the resulting Date
or DateTime
value after subtracting the specified period.
Example#
Use date_subtract()
to subtract a time period from a Date
or DateTime
value.
Alternatively, you can use the -
operator with a period constructor, such as date - days(7)
:
#import relationalai as rai
from relationalai.std import alias
from relationalai.std.dates import date, date_subtract, days
# Create a model named "events" with an `Event` type.
model = rai.Model("events")
Event = model.Type("Event")
# Add an event with a start date.
with model.rule():
# The event starts on January 8, 2021.
Event.add(name="Conference", start_date=date(2021, 1, 8))
# Subtract a duration of 7 days from the event start date.
with model.query() as select:
event = Event(name="Conference")
new_date = date_subtract(event.start_date, days(7))
# Or, use the `-` operator:
new_date = event.start_date - days(7)
response = select(event.name, alias(new_date, "new_date"))
print(response.results)
# Output:
# name new_date
# 0 Conference 2021-01-01
You can’t subtract sub-day time periods (e.g., hours, minutes, seconds) from a Date
:
#import relationalai as rai
from relationalai.std.dates import date, date_subtract, hours
model = rai.Model("dates")
# Subtracting hours from a date produces an empty result.
with model.query() as select:
my_date = date(2021, 1, 1) - hours(1)
response = select(my_date)
print(response.results)
# Output:
# Empty DataFrame
# Columns: []
# Index: []
To subtract sub-day time periods from a date, first convert the Date
to a DateTime
value:
#import relationalai as rai
from relationalai.std.dates import date, date_subtract, datetime, hours
model = rai.Model("dates")
# Convert the date to a datetime value before subtracting hours.
with model.query() as select:
my_date = datetime.fromdate(date(2021, 1, 1)) - hours(1)
response = select(my_date)
# NOTE: The result is a datetime.
print(response.results)
# Output:
# result
# 0 2020-12-31 23:00:00