date_range()#

relationalai.std.dates
#date_range(
    start: date|datetime|Producer|None = None,
    end: date|datetime|Producer|None = None,
    periods: int|Producer = 1,
    freq: str|Producer = "D"
) -> Expression

Creates a range of date or UTC datetime values between start and end with a specified number of periods and freq. If both start and end arguments are provided, they must both be dates or both be datetimes. If any of the arguments are Producer objects, then date_range() also acts as a filter and removes invalid values from the producer. Must be used within a rule or query context.

Parameters#

NameTypeDescription
startProducer, Python date or datetime, or NoneOptional left bound for generating dates. Must produce the same type of values as end, if provided. (Default: None)
endProducer, Python date or datetime, or NoneOptional right bound for generating dates. Must produce the same type of values as end, if provided. (Default: None)
periodsProducer or Python intOptional number of periods to generate. (Default: 1)
freqProducer or Python strThe frequency of the periods. Accepted values are:
  • "us": microseconds
  • "ms": milliseconds
  • "s": seconds
  • "m": minutes
  • "H": hours
  • "D": days (Default)
  • "W": weeks
  • "M": months
  • "Y": years

Returns#

An Expression object.

Example#

Use the date_range() function to create various ranges of dates and datetimes:

#import relationalai as rai
from relationalai.std import alias, dates


# =====
# SETUP
# =====

model = rai.Model("MyModel")
Event = model.Type("Event")
# Declare a multi-valued dates property for the Event type.
Event.dates.has_many()


# =======
# EXAMPLE
# =======

with model.rule():
    event1 = Event.add(id=1)
    event1.dates.extend([
        dates.date_range(dates.date(2023, 2, 1), dates.date(2023, 2, 3))
    ])

    event2 = Event.add(id=2)
    event2.dates.extend([
        dates.date_range(dates.date(2023, 3, 1), periods=4, freq='W')
    ])

with model.query() as select:
    event = Event()
    response = select(event.id, event.dates)

print(response.results)
#    id      dates
# 0   1 2023-02-01
# 1   1 2023-02-02
# 2   1 2023-02-03
# 3   2 2023-03-01
# 4   2 2023-03-08
# 5   2 2023-03-15
# 6   2 2023-03-22

If start or end is a date and a sub-day frequency is used, the range will be of datetime values:

#with model.query() as select:
    times = dates.date_range(dates.date(2023, 1, 1), periods=3, freq='H')
    response = select(alias(times, "time"))

print(response.results)
#                  time
# 0 2023-01-01 00:00:00
# 1 2023-01-01 01:00:00
# 2 2023-01-01 02:00:00

If periods is provided, only one of the start or end parameters is required:

#with model.query() as select:
    end_time = datetime(2023, 1, 1, 12)
    times = dates.date_range(end=end_time, periods=3, freq='H')
    response = select(alias(times, "time"))

print(response.results)
#                  time
# 0 2023-01-01 10:00:00
# 1 2023-01-01 11:00:00
# 2 2023-01-01 12:00:00

See Also#