Skip to content

Time Module

The time module provides utilities for working with dates and times in UTC, including ISO-8601 formatting, parsing, and common time operations.

Key Features

  • UTC Focus: All functions work exclusively with UTC timezone
  • ISO-8601 Formatting: Standardized timestamp formatting
  • Common Operations: Useful time manipulation functions
  • Type Safety: Proper typing for all functions

API Reference

Time and date utilities.

This module provides functions for working with dates and times in UTC, including ISO-8601 formatting, parsing, and common time operations.

Functions

end_of_day(dt=None)

Get the end of day (23:59:59.999999) for a given datetime.

Parameters:

Name Type Description Default
dt datetime | None

Input datetime (defaults to current UTC time if None)

None

Returns:

Name Type Description
datetime datetime

End of day (1 microsecond before midnight) in UTC timezone

Source code in spryx_core/time.py
def end_of_day(dt: datetime | None = None) -> datetime:
    """
    Get the end of day (23:59:59.999999) for a given datetime.

    Args:
        dt: Input datetime (defaults to current UTC time if None)

    Returns:
        datetime: End of day (1 microsecond before midnight) in UTC timezone
    """
    return start_of_day(dt) + timedelta(days=1, microseconds=-1)

now_utc()

Get the current UTC datetime.

Returns:

Name Type Description
datetime datetime

The current time in UTC timezone

Source code in spryx_core/time.py
def now_utc() -> datetime:
    """
    Get the current UTC datetime.

    Returns:
        datetime: The current time in UTC timezone
    """
    return datetime.now(timezone.utc)

parse_iso(value)

Parse an ISO-8601 UTC string into a datetime.

Parameters:

Name Type Description Default
value str

ISO-8601 string with Z suffix

required

Returns:

Name Type Description
datetime datetime

Parsed datetime with UTC timezone

Raises:

Type Description
ValueError

If the string is not in valid ISO-8601 UTC format

Source code in spryx_core/time.py
def parse_iso(value: str) -> datetime:
    """
    Parse an ISO-8601 UTC string into a datetime.

    Args:
        value: ISO-8601 string with Z suffix

    Returns:
        datetime: Parsed datetime with UTC timezone

    Raises:
        ValueError: If the string is not in valid ISO-8601 UTC format
    """
    if not ISO_8601_UTC_RE.fullmatch(value):
        raise ValueError("Formato ISO inválido")
    return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)

start_of_day(dt=None)

Get the start of day (00:00:00.000000) for a given datetime.

Parameters:

Name Type Description Default
dt datetime | None

Input datetime (defaults to current UTC time if None)

None

Returns:

Name Type Description
datetime datetime

Start of day (midnight) in UTC timezone

Source code in spryx_core/time.py
def start_of_day(dt: datetime | None = None) -> datetime:
    """
    Get the start of day (00:00:00.000000) for a given datetime.

    Args:
        dt: Input datetime (defaults to current UTC time if None)

    Returns:
        datetime: Start of day (midnight) in UTC timezone
    """
    dt = dt or now_utc()
    return dt.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=timezone.utc)

timestamp_from_iso(iso)

Convert an ISO-8601 UTC string to a UNIX timestamp.

Source code in spryx_core/time.py
def timestamp_from_iso(iso: str) -> int:
    """
    Convert an ISO-8601 UTC string to a UNIX timestamp.
    """
    return int(parse_iso(iso).timestamp())

to_iso(dt, *, milliseconds=False)

Convert a datetime to ISO-8601 format with Z suffix (UTC).

Parameters:

Name Type Description Default
dt datetime

The datetime to convert

required
milliseconds bool

If True, include milliseconds; otherwise, include microseconds

False

Returns:

Name Type Description
str str

ISO-8601 formatted string in UTC

Source code in spryx_core/time.py
def to_iso(dt: datetime, *, milliseconds: bool = False) -> str:
    """
    Convert a datetime to ISO-8601 format with Z suffix (UTC).

    Args:
        dt: The datetime to convert
        milliseconds: If True, include milliseconds; otherwise, include microseconds

    Returns:
        str: ISO-8601 formatted string in UTC
    """
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    dt = dt.astimezone(timezone.utc)

    if milliseconds:
        frac = f"{dt.microsecond // 1000:03d}"
        return dt.strftime(f"%Y-%m-%dT%H:%M:%S.{frac}Z")
    return dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

utc_from_timestamp(ts)

Convert a UNIX timestamp to a UTC datetime.

Parameters:

Name Type Description Default
ts int | float

UNIX timestamp (seconds since epoch)

required

Returns:

Name Type Description
datetime datetime

Corresponding datetime in UTC timezone

Source code in spryx_core/time.py
def utc_from_timestamp(ts: int | float) -> datetime:
    """
    Convert a UNIX timestamp to a UTC datetime.

    Args:
        ts: UNIX timestamp (seconds since epoch)

    Returns:
        datetime: Corresponding datetime in UTC timezone
    """
    return datetime.fromtimestamp(ts, tz=timezone.utc)

Usage Examples

Current UTC Time

from spryx_core import now_utc

# Get current UTC time
current_time = now_utc()
print(current_time)  # Example: 2023-12-01 14:32:15.123456+00:00

ISO-8601 Formatting

from spryx_core import now_utc, to_iso

# Format current time as ISO-8601
current_time = now_utc()
iso_format = to_iso(current_time)
print(iso_format)  # Example: 2023-12-01T14:32:15.123456Z

# Format with millisecond precision
iso_ms = to_iso(current_time, milliseconds=True)
print(iso_ms)  # Example: 2023-12-01T14:32:15.123Z

Parsing ISO-8601 Timestamps

from spryx_core import parse_iso

# Parse ISO-8601 string to datetime
dt = parse_iso("2023-12-01T14:32:15Z")
print(dt)  # 2023-12-01 14:32:15+00:00

Day Boundaries

from spryx_core import start_of_day, end_of_day, now_utc

today = now_utc()

# Get midnight (00:00:00.000000)
day_start = start_of_day(today)
print(day_start)  # Example: 2023-12-01 00:00:00+00:00

# Get last moment of day (23:59:59.999999)
day_end = end_of_day(today)
print(day_end)  # Example: 2023-12-01 23:59:59.999999+00:00

# Date range for "today"
print(f"Today spans from {day_start} to {day_end}")

Converting Timestamps

from spryx_core.time import utc_from_timestamp

# Convert UNIX timestamp to UTC datetime
unix_timestamp = 1701443535  # Seconds since epoch
dt = utc_from_timestamp(unix_timestamp)
print(dt)  # Example: 2023-12-01 14:32:15+00:00

Best Practices

  1. Always Use UTC: For any timestamp storage or processing, use UTC timezone.
  2. Store in ISO Format: When storing timestamps as strings, use ISO-8601 format.
  3. Consistent Format: Use the to_iso() function to ensure consistent formatting.