datetime.fromdate()#

relationalai.std.dates
#datetime.fromdate(
    date: date|Producer
    hour: int|Producer = 0,
    minute: int|Producer = 0,
    second: int|Producer = 0,
    millisecond: int|Producer = 0
    tz: tzinfo|str|Producer = "UTC"
) -> Expression

Constructs a UTC datetime value from a date value. If date or one of the time components is a Producer object, then datetime.fromdate() also acts as a filter and removes invalid values from the producer. If tz is specified, the datetime is converted to UTC from the specified timezone or offset string. Must be called in a rule or query context.

Parameters#

NameTypeDescription
datedate or ProducerThe Date value to convert to DateTime.

Returns#

An Expression object.

Example#

Use datetime.fromdate() to construct a UTC datetime value from a date value:

#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(date=dates.date(2021, 1, 1), hour=9, minute=30)
    Event.add(id=2).set(date="invalid", hour=10, minute=30)


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

with model.rule():
    event = Event()
    # Since Event 2 has an invalid date, datetime.fromdate() will filter it out
    # and the following will only set the time property for Event 1.
    event.set(
        time=dates.datetime.fromdate(event.date, event.hour, event.minute)
    )
    # The following only sets the has_valid_date property for Event 1.
    event.set(has_valid_date=True)

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

print(response.results)
#    id                time has_valid_date
# 0   1 2021-01-01 09:30:00           True
# 1   2                 NaT            NaN

If the tz parameter is specified, the datetime is converted to UTC from the specified timezone or offset string:

#with model.query() as select:
    event = Event(id=1)
    time_tz = dates.datetime.fromdate(event.date, event.hour, event.minute, tz="America/New_York")
    response = select(event.time, alias(time_tz, "time_tz"))

print(response.results)
#                  time             time_tz
# 0 2021-01-01 09:30:00 2021-01-01 14:30:00

Refer to the timezone database for a list of valid timezone identifiers.

See Also#