Skip to content

timeframe

timeframe

Classes:

Name Description
TimeFrame

Pre-defined TimeFrame values

Functions:

Name Description
on_timeframe

Checks if timestamp is on a timeframe value

round_down_timestamp

Find and round down timestamp to the nearest matching timeframe. E.G timeframe of 5 minute

within_timeframe

Checks if timestamp is within other timestamp and timeframe period

TimeFrame

Bases: Enum

Pre-defined TimeFrame values

on_timeframe

on_timeframe(timestamp: datetime, timeframe: timedelta) -> bool

Checks if timestamp is on a timeframe value

Source code in hexital/utils/timeframe.py
def on_timeframe(timestamp: datetime, timeframe: timedelta) -> bool:
    """Checks if timestamp is on a timeframe value"""
    return timestamp.timestamp() % timeframe.total_seconds() == 0

round_down_timestamp

round_down_timestamp(timestamp: datetime, timeframe: timedelta) -> datetime

Find and round down timestamp to the nearest matching timeframe. E.G timeframe of 5 minute E.G T5: 09:00:01 -> 9:00:00 E.G T5: 09:01:20 -> 9:00:00 E.G T5: 09:05:00 -> 9:05:00 Note: This method also calls trim_timestamp, removing microseconds

Source code in hexital/utils/timeframe.py
def round_down_timestamp(timestamp: datetime, timeframe: timedelta) -> datetime:
    """Find and round down timestamp to the nearest matching timeframe. E.G timeframe of 5 minute
    E.G T5: 09:00:01 -> 9:00:00
    E.G T5: 09:01:20 -> 9:00:00
    E.G T5: 09:05:00 -> 9:05:00
    Note: This method also calls trim_timestamp, removing microseconds
    """
    timestamp = timestamp.replace(microsecond=0)

    if timeframe < timedelta(days=1):
        seconds = timeframe.total_seconds()
        rounded_ts = (timestamp.timestamp() // seconds) * seconds
        return datetime.fromtimestamp(rounded_ts, tz=timestamp.tzinfo)

    if timeframe >= timedelta(days=7):
        days_since_monday = timestamp.isoweekday() - 1
        return (timestamp - timedelta(days=days_since_monday)).replace(
            hour=0, minute=0, second=0
        )

    return timestamp.replace(hour=0, minute=0, second=0)

within_timeframe

within_timeframe(
    timestamp: datetime, within: datetime, timeframe: timedelta | None
) -> bool

Checks if timestamp is within other timestamp and timeframe period

Source code in hexital/utils/timeframe.py
def within_timeframe(
    timestamp: datetime, within: datetime, timeframe: timedelta | None
) -> bool:
    """Checks if timestamp is within other timestamp and timeframe period"""
    if not timeframe:
        return False
    return within - timeframe < timestamp <= within