Skip to content

Time Tool

The CurrentTimeTool provides time-related operations and utilities for agents in the Bedrock Swarm framework. It handles current time retrieval, timezone conversions, and time offsets.

Class Documentation

Bases: BaseTool

Tool for getting current time and calculating future times.

PARAMETER DESCRIPTION
name

Name of the tool

TYPE: str DEFAULT: 'current_time'

description

Description of the tool

TYPE: str DEFAULT: 'Get the current time and date in various formats and timezones'

Source code in src/bedrock_swarm/tools/time.py
def __init__(
    self,
    name: str = "current_time",
    description: str = "Get the current time and date in various formats and timezones",
) -> None:
    """Initialize the time tool.

    Args:
        name: Name of the tool
        description: Description of the tool
    """
    self._name = name
    self._description = description

Attributes

name: str property

Get tool name.

description: str property

Get tool description.

Functions

get_schema() -> Dict[str, Any]

Get JSON schema for the time tool.

Source code in src/bedrock_swarm/tools/time.py
def get_schema(self) -> Dict[str, Any]:
    """Get JSON schema for the time tool."""
    return {
        "name": self.name,
        "description": self.description,
        "parameters": {
            "type": "object",
            "properties": {
                "timezone": {
                    "type": "string",
                    "description": "Timezone to get time in (e.g. 'UTC', 'US/Pacific'). Defaults to local timezone.",
                },
                "minutes_offset": {
                    "type": "integer",
                    "description": "Optional number of minutes to add to current time",
                },
            },
            "required": [],
        },
    }

_normalize_timezone(timezone: str) -> str

Normalize timezone name.

PARAMETER DESCRIPTION
timezone

Timezone name to normalize

TYPE: str

RETURNS DESCRIPTION
str

Normalized timezone name

RAISES DESCRIPTION
ValueError

If timezone is invalid

Source code in src/bedrock_swarm/tools/time.py
def _normalize_timezone(self, timezone: str) -> str:
    """Normalize timezone name.

    Args:
        timezone: Timezone name to normalize

    Returns:
        Normalized timezone name

    Raises:
        ValueError: If timezone is invalid
    """
    # Common aliases
    aliases = {
        "EST": "America/New_York",
        "EDT": "America/New_York",
        "CST": "America/Chicago",
        "CDT": "America/Chicago",
        "MST": "America/Denver",
        "MDT": "America/Denver",
        "PST": "America/Los_Angeles",
        "PDT": "America/Los_Angeles",
        "JST": "Asia/Tokyo",
        "GMT": "UTC",
    }

    # Try alias first
    if timezone.upper() in aliases:
        return aliases[timezone.upper()]

    # Try as is
    if timezone in available_timezones():
        return timezone

    # Try common variations
    variations = [
        timezone,
        timezone.upper(),
        timezone.lower(),
        timezone.title(),
        f"Etc/{timezone}",
    ]

    for var in variations:
        if var in available_timezones():
            return var

    raise ValueError(f"Invalid timezone: {timezone}")

_execute_impl(*, timezone: Optional[str] = None, minutes_offset: Optional[int] = None, **kwargs: Any) -> str

Execute the time tool.

PARAMETER DESCRIPTION
timezone

Timezone to get time in (defaults to local timezone)

TYPE: Optional[str] DEFAULT: None

minutes_offset

Optional number of minutes to add to current time

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION
str

Current or future time in specified timezone

Source code in src/bedrock_swarm/tools/time.py
def _execute_impl(
    self,
    *,
    timezone: Optional[str] = None,
    minutes_offset: Optional[int] = None,
    **kwargs: Any,
) -> str:
    """Execute the time tool.

    Args:
        timezone: Timezone to get time in (defaults to local timezone)
        minutes_offset: Optional number of minutes to add to current time

    Returns:
        Current or future time in specified timezone
    """
    try:
        # Use local timezone if none specified
        tz = None
        if timezone:
            normalized_tz = self._normalize_timezone(timezone)
            tz = ZoneInfo(normalized_tz)

        # Get current time in specified timezone
        current = datetime.now(tz)

        # Add offset if specified
        if minutes_offset is not None:
            current += timedelta(minutes=minutes_offset)

        # Format the time
        return current.strftime("%Y-%m-%d %H:%M:%S %Z")

    except Exception as e:
        raise ValueError(f"Error getting time: {str(e)}")

Features

The time tool provides:

  1. Current time operations:
  2. Get current time in any timezone
  3. Support for timezone aliases (EST, PST, etc.)
  4. Optional time offset in minutes

  5. Time formatting:

  6. ISO-like format (YYYY-MM-DD HH:MM:SS TZ)
  7. Timezone information included

  8. Timezone handling:

  9. Support for all IANA timezone names
  10. Common timezone aliases
  11. Flexible timezone name matching

Usage Examples

from bedrock_swarm.tools import CurrentTimeTool

# Initialize the tool
time_tool = CurrentTimeTool()

# Get current time in local timezone
result = time_tool.execute()
print(result)  # Output: 2024-02-29 15:30:45 PST

# Get current time in UTC
result = time_tool.execute(timezone="UTC")
print(result)  # Output: 2024-02-29 23:30:45 UTC

# Get time with offset
result = time_tool.execute(timezone="EST", minutes_offset=30)
print(result)  # Output: 2024-02-29 18:00:45 EST

# Using timezone aliases
result = time_tool.execute(timezone="PST")  # Automatically maps to America/Los_Angeles
print(result)  # Output: 2024-02-29 15:30:45 PST

Error Handling

The time tool handles various error cases:

  1. Invalid timezone names
  2. Timezone conversion errors
  3. Invalid time offsets
  4. General execution errors

Implementation Details

The time tool:

  1. Uses Python's datetime and zoneinfo libraries
  2. Supports all IANA timezone names
  3. Provides common timezone aliases
  4. Includes timezone name normalization
  5. Handles timezone-aware datetime objects