second()#

relationalai.std.dates
#second(date: datetime|Producer, tz: str|Producer = "UTC") -> Expression

Extracts the second component from a UTC datetime value. If tz is specified, then date is converted from UTC to the specified timezone before extracting the second. tz is ignored if date is a Python datetime object. If any of the arguments are Producer objects, then second() also acts as a filter and removes invalid values from the producer, including dates. Must be called in a rule or query context.

Parameters#

NameTypeDescription
dateProducer or Python datetime objectThe datetime value from which to extract the second.
tzProducer or Python str objectOptional timezone string (e.g., "America/New_York"), offset string (e.g., "+0600"), or Python tzinfo object. Refer to the timezone database for a list of valid timezone identifiers. Ignored if date is a Python datetime object. (Default: "UTC").

Returns#

An Expression object.

Raises#

TypeError if the date parameter is not a Producer object or Python date or datetime object.

Example#

Use second() to extract the second component from UTC datetime values:

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


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

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

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


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

with model.rule():
    event = Event()
    # second() filters out any events with invalid time values, so the
    # following only sets the second property for Event 1.
    event.set(second=dates.second(event.time))
    # 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, event.second, event.has_valid_time)

print(response.results)
#    id                 time  second has_valid_time
# 0   1  2021-01-01 01:30:45    45.0           True
# 1   2              invalid     NaN            NaN

If the tz parameter is specified, the datetime is converted from UTC to the specified timezone before extracting the second:

#with model.query() as select:
    event = Event()
    second1 = dates.second(event.time, tz="America/New_York")
    second2 = dates.second(event.time, tz="+0600")
    response = select(event.id, event.time, alias(second1, "second1"), alias(second2, "second2"))

print(response.results)
#    id                time  second1  second2
# 0   1 2021-01-01 01:30:45       45       45

Note that second() does not return 0 for date values. Instead, because second() expects a datetime value, date values are filtered out:

#with model.query() as select:
    date = dates.date(2021, 1, 1)
    response = select(dates.second(date))

print(response.results)
# Empty DataFrame
# Columns: []
# Index: []

See Also#