Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

4.7 KB
Raw Blame
import datetime
from math import floor
from typing import Any, Optional, Union


def format_matrix(matrix: list[list[Any]]) -> str:
    # Coerce cells: a None (or non-str) cell would make "|".join raise and crash the build.
    lines: list[str] = []
    for row in matrix:
        lines.append("|".join("" if cell is None else str(cell) for cell in row))

    return "\n".join(lines).strip()


def format_number(value: Any) -> str:
    if value is None:
        return "N/A"

    try:
        num = float(value)
        if num.is_integer():
            return str(int(num))
        return f"{num:.5f}".rstrip("0")
    except ValueError:
        return str(value)


def format_percentage(value: float | int) -> str:
    num = float(value) * 100
    formatted = f"{num:.2f}".rstrip("0").rstrip(".")
    return f"{formatted}%"


def format_duration(
    d: Union[str, int, float, None],
    max_units: Optional[int] = None,
    seconds_precision: Optional[int] = None,
    seconds_fixed: Optional[int] = None,
) -> str:
    """Convert seconds to a human-readable duration string.
    Example: `1d 10hrs 9mins 8s`

    Args:
        d: Duration in seconds
        max_units: Maximum number of units to display
        seconds_precision: Precision for seconds (significant figures)
        seconds_fixed: Fixed decimal places for seconds

    Returns:
        Human readable duration string
    """
    if not d or max_units == 0:
        return ""

    try:
        d = float(d)
    except (ValueError, TypeError):
        return ""

    if d < 0:
        return f"-{format_duration(-d, max_units, seconds_precision, seconds_fixed)}"

    if d == 0:
        return "0s"

    if d < 1:
        return f"{round(d * 1000)}ms"

    if d < 60:
        if seconds_precision is not None:
            # Round to significant figures and strip trailing .0
            return f"{float(f'%.{seconds_precision}g' % d):.0f}s".replace(".0s", "s")
        # Round to fixed decimal places and strip trailing .0
        fixed = seconds_fixed if seconds_fixed is not None else 0
        return f"{float(f'%.{fixed}f' % d):.0f}s".replace(".0s", "s")

    days = floor(d / 86400)
    h = floor((d % 86400) / 3600)
    m = floor((d % 3600) / 60)
    s = round((d % 3600) % 60)

    day_display = f"{days}d" if days > 0 else ""
    h_display = f"{h}h" if h > 0 else ""
    m_display = f"{m}m" if m > 0 else ""
    s_display = f"{s}s" if s > 0 else ("0s" if not (h_display or m_display) else "")

    if days > 0:
        units = [u for u in [day_display, h_display] if u]
    else:
        units = [u for u in [h_display, m_display, s_display] if u]

    if max_units is not None:
        units = units[:max_units]

    return " ".join(units)


def format_date(date: datetime.date) -> str:
    return date.strftime("%Y-%m-%d")


def strip_datetime_seconds(date: str) -> str:
    return datetime.datetime.fromisoformat(date).strftime("%Y-%m-%d %H:%M" if ":" in date else "%Y-%m-%d")


# Appended to a bucket's date cell when that bucket is still collecting data.
PARTIAL_BUCKET_MARKER = " (partial)"


def parse_bucket_datetime(day: str) -> Optional[datetime.datetime]:
    """Parse a trends/funnel bucket label into a naive datetime (project-local).

    Bucket labels are `%Y-%m-%d` or `%Y-%m-%d %H:%M:%S` strings emitted in the project
    timezone. Returns None if the label can't be parsed, so callers fall back to not
    flagging the bucket rather than crashing on an unexpected format."""
    for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
        try:
            return datetime.datetime.strptime(day, fmt)
        except ValueError:
            continue
    try:
        return datetime.datetime.fromisoformat(day).replace(tzinfo=None)
    except ValueError:
        return None


def partial_bucket_flags(days: list[str], current_interval_start: datetime.datetime) -> list[bool]:
    """Flag each bucket that falls in the current (still-collecting) interval or later.

    `current_interval_start` is the start of the interval containing "now", in project-local
    naive time. A bucket at or after it hasn't finished accruing data yet, so its value is
    partial — this is what makes daily/hourly automation over trends results unsafe when the
    last row is silently incomplete or labeled in the future."""
    flags: list[bool] = []
    for day in days:
        bucket_start = parse_bucket_datetime(day)
        flags.append(bucket_start is not None and bucket_start >= current_interval_start)
    return flags


def partial_bucket_note(timezone: str) -> str:
    return (
        f'Note: rows marked "{PARTIAL_BUCKET_MARKER.strip()}" cover an interval that is still in progress '
        f"as of the query time, so their values are incomplete. Timezone: {timezone}."
    )