date_add()#

relationalai.std.dates
#date_add(
    date: date | datetime | Producer,
    period: Producer
) -> Expression

Adds a time period to a Date or DateTime value. Must be called in a rule or query context.

Parameters#

NameTypeDescription
datedate or datetime or ProducerThe Date or DateTime value to which to add the time period.
periodProducerThe time period to add (e.g., day(), week(), month(), year()).

Returns#

An Expression that produces the resulting Date or DateTime value after adding the specified period.

Example#

Use date_add() to add a time period to 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_add, 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 1, 2021.
    Event.add(name="Conference", start_date=date(2021, 1, 1))

# Add a duration of 7 days to the event start date.
with model.query() as select:
    event = Event(name="Conference")
    new_date = date_add(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-08

You can’t add sub-day time periods (e.g., hours, minutes, seconds) to a Date:

#import relationalai as rai
from relationalai.std.dates import date, date_add, hours

model = rai.Model("dates")

# Adding hours to 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 add sub-day time periods to a date, first convert the Date to a DateTime value:

#import relationalai as rai
from relationalai.std.dates import date, date_add, datetime, hours

model = rai.Model("dates")

# Convert the date to a datetime value before adding 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 2021-01-01 01:00:00

See Also#