strftime()#

relationalai.std.dates
#strftime(date: date|datetime|Producer, format: str|Producer) -> Expression

Formats a date or datetime value as a string according to format. If date or format are Producer objects, then strftime() also acts as a filter and removes non-date values and invalid format strings from the producers. Must be called in a rule or query context.

IMPORTANT

The format codes used by RAI’s strftime() are different from Python’s datetime.strftime() function. See Format Codes for details.

Parameters#

NameTypeDescription
dateProducer or Python date or datetime objectThe date or datetime value to format as a string.
formatProducer or Python str objectThe format string to format the date or datetime value. See Format Codes for supported format codes.

Returns#

An Expression object.

Example#

Use strftime() to format a date or datetime value as a string according to a format string:

#import relationalai as rai
from relationalai.std import dates


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

model = rai.Model("MyModel")
Event = model.Type("Event")

with model.rule():
    Event.add(id=1).set(time=dates.datetime(2021, 1, 1, 9, 30))
    Event.add(id=2).set(time="invalid")


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

with model.rule():
    event = Event()
    # strftime() filters out any events with invalid time values, so the
    # following only sets the time property for Event 1.
    event.set(time_str=dates.strftime(event.time, "d/m/y I:M:S p"))
    # Since Event 2 is filtered out above, the following only sets the
    # has_valid_time property for Event 1.
    event.set(has_valid_time=True)

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

print(response.results)
#    id         time_str has_valid_time
# 0   1  1/1/1 9:30:0 AM           True
# 1   2              NaN            NaN

Common ISO 8601 formats can be accessed using the ISO namespace:

#with model.query() as select:
    event = Event()
    time_str = dates.strftime(event.time, dates.ISO.SECONDS)
    response = select(event.id, time_str)

print(response.results)
#    id                    v
# 0   1  2021-01-01T09:30:00

See Format Codes for more details on the format codes used in RAI format strings.

See Also#