"""
Herramientas relacionadas con fecha y hora.
"""
import calendar
from datetime import datetime, timezone
from typing import Any, Dict
def get_current_time(args: Dict[str, Any]) -> str:
"""Obtener la fecha y hora actual."""
timezone_name = args.get("timezone", "UTC")
format_str = args.get("format", "%Y-%m-%d %H:%M:%S")
if timezone_name == "UTC":
now = datetime.now(timezone.utc)
else:
# Para simplicidad, usar timezone local
now = datetime.now()
return f"Fecha y hora actual: {now.strftime(format_str)} ({timezone_name})"
def format_timestamp(args: Dict[str, Any]) -> str:
"""Formatear un timestamp Unix a fecha legible."""
timestamp = args.get("timestamp")
format_str = args.get("format", "%Y-%m-%d %H:%M:%S")
if not timestamp:
return "Error: Se requiere el parámetro 'timestamp'"
try:
dt = datetime.fromtimestamp(float(timestamp))
return f"Fecha formateada: {dt.strftime(format_str)}"
except (ValueError, TypeError) as e:
return f"Error formateando timestamp: {str(e)}"
def calculate_age(args: Dict[str, Any]) -> str:
"""Calcular la edad basada en fecha de nacimiento."""
birth_date_str = args.get("birth_date")
if not birth_date_str:
return "Error: Se requiere el parámetro 'birth_date' (formato: YYYY-MM-DD)"
try:
birth_date = datetime.strptime(birth_date_str, "%Y-%m-%d")
today = datetime.now()
age = today.year - birth_date.year
if today.month < birth_date.month or (
today.month == birth_date.month and today.day < birth_date.day
):
age -= 1
return f"Edad: {age} años"
except ValueError as e:
return f"Error en formato de fecha: {str(e)}. Use formato YYYY-MM-DD"
def days_between_dates(args: Dict[str, Any]) -> str:
"""Calcular días entre dos fechas."""
start_date_str = args.get("start_date")
end_date_str = args.get("end_date")
if not start_date_str or not end_date_str:
return "Error: Se requieren los parámetros 'start_date' y 'end_date' (formato: YYYY-MM-DD)"
try:
start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
diff = end_date - start_date
return f"Diferencia: {diff.days} días"
except ValueError as e:
return f"Error en formato de fecha: {str(e)}. Use formato YYYY-MM-DD"
def get_calendar_month(args: Dict[str, Any]) -> str:
"""Mostrar calendario de un mes específico."""
year = args.get("year", datetime.now().year)
month = args.get("month", datetime.now().month)
try:
cal = calendar.month(int(year), int(month))
return f"Calendario para {month}/{year}:\n{cal}"
except (ValueError, calendar.IllegalMonthError) as e:
return f"Error generando calendario: {str(e)}"
def register_datetime_tools(tools: Dict[str, Dict[str, Any]]) -> None:
"""Registrar herramientas de fecha y hora."""
tools["get_current_time"] = {
"description": "Obtener la fecha y hora actual con formato personalizable",
"handler": get_current_time,
"inputSchema": {
"type": "object",
"properties": {
"timezone": {
"type": "string",
"description": "Zona horaria (por defecto: UTC)",
"default": "UTC",
},
"format": {
"type": "string",
"description": "Formato de fecha (por defecto: %Y-%m-%d %H:%M:%S)",
"default": "%Y-%m-%d %H:%M:%S",
},
},
},
}
tools["format_timestamp"] = {
"description": "Convertir timestamp Unix a fecha legible",
"handler": format_timestamp,
"inputSchema": {
"type": "object",
"properties": {
"timestamp": {
"type": "number",
"description": "Timestamp Unix a convertir",
},
"format": {
"type": "string",
"description": "Formato de salida (por defecto: %Y-%m-%d %H:%M:%S)",
"default": "%Y-%m-%d %H:%M:%S",
},
},
"required": ["timestamp"],
},
}
tools["calculate_age"] = {
"description": "Calcular edad basada en fecha de nacimiento",
"handler": calculate_age,
"inputSchema": {
"type": "object",
"properties": {
"birth_date": {
"type": "string",
"description": "Fecha de nacimiento (formato: YYYY-MM-DD)",
}
},
"required": ["birth_date"],
},
}
tools["days_between_dates"] = {
"description": "Calcular días entre dos fechas",
"handler": days_between_dates,
"inputSchema": {
"type": "object",
"properties": {
"start_date": {
"type": "string",
"description": "Fecha inicial (formato: YYYY-MM-DD)",
},
"end_date": {
"type": "string",
"description": "Fecha final (formato: YYYY-MM-DD)",
},
},
"required": ["start_date", "end_date"],
},
}
tools["get_calendar_month"] = {
"description": "Mostrar calendario de un mes específico",
"handler": get_calendar_month,
"inputSchema": {
"type": "object",
"properties": {
"year": {
"type": "integer",
"description": "Año (por defecto: año actual)",
},
"month": {
"type": "integer",
"description": "Mes (1-12, por defecto: mes actual)",
"minimum": 1,
"maximum": 12,
},
},
},
}