Metadata-Version: 2.4
Name: chronos-timetool
Version: 0.1.0
Summary: A Python library for quickly manipulating time and obtain time data.
Author-email: Pedro Antonio Rodrigues <pedro.a.rodrigues7@gmail.com>
License-File: LICENSE
Keywords: chronos,datetime,time,timer,timetool,tool
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.9
Requires-Dist: babel>=2.10.0
Requires-Dist: parsedatetime>=2.6
Requires-Dist: python-dateutil>=2.8.2
Requires-Dist: pytz>=2022.1
Description-Content-Type: text/markdown


# Chronos Timetool

**A Swiss Army knife for time manipulation in Python.**

![Python Version](https://img.shields.io/badge/python-3.8%2B-orange)
![Version](https://img.shields.io/badge/version-0.1.0-brown)
![License](https://img.shields.io/badge/license-MIT-red)
![Maintained](https://img.shields.io/badge/maintained-yes-green)

Chronos is a comprehensive library designed to handle all your time-related needs: parsing, formatting, timezone management, business day calculations, humanized durations, performance profiling, and much more. It combines robust parsing engines, intuitive APIs, and extensive utilities to make working with dates and times effortless. The library and all classes are heavily typed, and completely secure to any task you'd need Chronos.

---

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Core Module (`core.py`)](#core-module-corepy)
  - [Chronos Class](#chronos-class)
  - [Countries Class](#countries-class)
  - [Time Class](#time-class)
- [Parser Module (`parser.py`)](#parser-module-parserpy)
- [Utils Module (`utils.py`)](#utils-module-utilspy)
- [Packages & Exceptions](#packages--exceptions)
- [Examples](#examples)
- [Contributing](#contributing)
- [License](#license)

---

## Features

- ⏱ **High‑precision stopwatch** and function profiling decorators
- 🌍 **Country information** – get GMT/UTC offsets, locale formats, capitals, currencies
- 🧠 **Smart parsing** – accepts timestamps, ISO strings, regional formats, and even natural language (“next Friday”)
- 📅 **Business day calculations** – skip weekends and holidays
- 🗓 **Humanized time differences** (“3 days ago”, “in 2 hours”) with locale support
- 🕒 **Timezone‑aware** – work with UTC, GMT offsets, and DST detection
- 🔄 **Duration parsing** – convert “2h 30min” into seconds, minutes, etc.
- 📁 **Safe timestamp slugs** for file names and IDs
- 🔁 **Retry decorator** with exponential backoff
- 🖥 **Terminal utilities** – colorful ASCII art, countdowns, and clean output

---

## Installation

```bash
pip install chronos-timetool
```

Chronos requires Python 3.8+ and depends on:

- `babel` – for locale‑aware formatting
- `python-dateutil` – for flexible parsing
- `pytz` – for timezone handling
- `countryinfo` – for offline country data
- `parsedatetime` – for natural language detection

These are automatically installed with the package.

---

## Core Module (`core.py`)

The heart of Chronos. It provides three main classes: `Chronos`, `Countries`, and `Time`.

### Chronos Class

Utility methods and decorators for everyday tasks.

#### `@Chronos.profile(verbose=True)`

Measures and prints the execution time of a function.

```python
from chronos import Chronos

@Chronos.profile(verbose=True)
def heavy_computation():
    # ... do work
    return result
```

#### `@Chronos.retry(retries=3, delay=1.0, verbose=True)`

Automatically retries a function on exception.

```python
@Chronos.retry(retries=5, delay=2)
def fetch_api():
    # network call
    pass
```

#### `Chronos.countdown(seconds, message, show_prefix)`

Displays a clean countdown in the terminal.

```python
Chronos.countdown(5, "Server starting", show_prefix=True)
```

#### `Chronos.sleep(seconds)`

A safe sleep wrapper that ensures a positive integer delay.

#### `Chronos.Stopwatch`

Context‑manager stopwatch with pause/resume and multiple units.

```python
with Chronos.Stopwatch() as sw:
    # do work
    print(sw.elapsed(unit="ms"))  # "123.456 ms"
```

---

### Countries Class

Retrieve geographical and timezone information for any country.

```python
from chronos import Countries

jp = Countries("japan")
print(jp.get_GMT())      # "+9"
print(jp.get_UTC())      # "+9"
print(jp.get_FORMAT())   # "ja-JP"
print(jp.get_info())     # {'capital': 'Tokyo', 'currencies': ['JPY'], ...}
```

Supports country names (full or partial), alpha‑2 codes, alpha‑3 codes, and many language aliases.

---

### Time Class

The central class for time manipulation, localization, and calculations.

#### Instantiation with options

```python
from chronos import Time

# Default: UTC+0, en‑US, 24‑hour format
t = Time()

# Custom timezone, locale, and 12‑hour clock
t = Time(options={
    "UTC": "+5:30",        # India
    "FORMAT": "hi-IN",
    "AM_PM": True,
    "BASE_TIME": "2026-01-01 12:00"
})
```

Available options:

- `UTC` / `GMT` – offset string (e.g., `"+5:30"`) or float
- `FORMAT` – locale string (e.g., `"pt-BR"`)
- `LOCAL` – boolean; if `True`, uses local system timezone
- `AM_PM` – boolean; `True` for 12‑hour display
- `BASE_TIME` – any parseable date/time to use as reference

#### Key methods

- **`time()`** – returns the current (or base) datetime in the configured timezone.
- **`smart_parse(raw)`** – universal parser: handles timestamps, ISO, localized formats.
- **`is_expired(target, against=None)`** – checks if a date has passed.
- **`range(target)`** – difference between base and target in years, months, days, etc.
- **`calculate(years=0, months=0, ...)`** – add/subtract units from base time.
- **`humanize(against)`** – returns relative text like “2 days ago” (locale‑aware).
- **`age()`** – exact age from `BASE_TIME` to now.
- **`is_legal_age(limit=18)`** – checks if age >= limit.
- **Business day helpers** – `next_business_day()`, `next_business_days(n)`, `last_business_day_of_month()`.
- **`overlaps(start_A, end_A, start_B, end_B)`** – interval overlap check.
- **`is_weekend()`, `is_business_day()`** – boolean checks.
- **`start_of_day()`, `end_of_day()`** – trim to boundaries.
- **`to_iso()`, `to_rfc2822()`** – standard format outputs.
- **`is_dst(timezone)`, `is_ambiguous(timezone)`** – DST detection and ambiguity.

---

## Parser Module (`parser.py`)

A standalone engine for parsing, converting, and transforming temporal data with extreme flexibility.

### `Parser._to_datetime(item)`

Internal but exposed as a robust entry point. Accepts:

- Python `datetime` objects
- Integers/floats (Unix timestamps, auto‑scaling milliseconds)
- Strings – ISO, regional, logs with embedded dates, and natural language (via fallback)

```python
from chronos.parser import Parser

dt = Parser._to_datetime("ERROR [2026-07-07 14:30:00] - crash")  # returns datetime
```

### `Parser.convert(item, to, gmt_shift=None)`

Transform any input into one of four formats:

- `"datetime"` – returns a `datetime` object
- `"posix"` – returns Unix timestamp (float)
- `"iso"` – returns ISO 8601 string
- `"dict"` – returns dictionary with `year`, `month`, `day`, `hour`, `minute`, `second`

Optionally apply a GMT shift on the fly.

```python
# From natural language to Unix timestamp
ts = Parser.convert("next monday", to="posix")

# Timestamp to ISO with +3 hours
iso = Parser.convert(1722000000, to="iso", gmt_shift=3)
```

### `Parser.transform(years=0, months=0, ..., to="seconds", base_time=None)`

Converts a combination of time units into a single unit with calendar‑precision.

```python
# How many days in 2 years and 1 month?
days = Parser.transform(years=2, months=1, to="days")  # ~761 days (leap years considered)

# Using a specific base (e.g., during a leap year)
days_feb = Parser.transform(months=1, to="days", base_time="2024-01-01")  # 29
```

### `Parser.parse_duration(duration_str, to="seconds", base_time=None)`

Parses human‑readable durations like `"2h 30min"` or `"1.5 days"` and returns the value in the requested unit.

```python
seconds = Parser.parse_duration("1d 12h")        # 129600.0
minutes = Parser.parse_duration("2.5 hours", to="minutes")  # 150.0
```

### `Parser.detect(string, base_time=None)`

Uses `parsedatetime` to interpret natural language expressions relative to a given base time.

```python
dt = Parser.detect("in 2 weeks")                # datetime 2 weeks from now
past = Parser.detect("3 days ago", base_time="2026-07-01")  # 2026-06-28
```

---

## Utils Module (`utils.py`)

Helper functions for common tasks.

### `Utils.is_leap_year(item)`

Checks if a year (or date) is a leap year.

```python
from chronos.utils import Utils

u = Utils()
u.is_leap_year(2024)      # True
u.is_leap_year("2023")    # False
u.is_leap_year("2024-02-29")  # True
```

### `Utils.timestamp_slug(base_time=None, compact=False)`

Generates a clean timestamp string for file names or IDs.

```python
u.timestamp_slug()                     # "2026-07-08_14-30-15"
u.timestamp_slug(compact=True)         # "20260708143015"
```

### `Utils.days_in_month(month, year=None)`

Number of days in a given month (handles leap years).

```python
u.days_in_month(2, 2024)   # 29
u.days_in_month(2, 2023)   # 28
```

### `Utils.quarter(item=None)` and `Utils.week_of_year(item=None)`

Return the fiscal quarter (1‑4) and ISO week number (1‑53) for any date.

---

## Packages & Exceptions

- **`packages.py`** – contains constants, default values, unit mappings, country alpha‑3 codes, ASCII art alphabet, and a `Tools` class with rounding, type checking, and limit functions.
- **`exceptions.py`** – custom exceptions for clear error handling:
  - `ParserErrorException`
  - `HumanizerErrorException`
  - `CountryCodeNotFoundException`
  - `IsLeapYearValueErrorException`
  - `TimestampSlugValueErrorException`

---

## Examples

### 1. Profile a function and retry on failure

```python
from chronos import Chronos, Time

@Chronos.profile(verbose=True)
@Chronos.retry(retries=3)
def fetch_data():
    # simulate flaky API
    pass

fetch_data()
```

### 2. Get business days between two dates

```python
from chronos import Time

t = Time(options={"BASE_TIME": "2026-07-01"})
next_three = t.next_business_days(3)  # list of datetimes
last = t.last_business_day_of_month(holidays=["2026-07-04"])
```

### 3. Parse dirty log entries

```python
from chronos.parser import Parser

log = "ERROR [2026-07-07 14:30:00] - Disk full"
iso = Parser.convert(log, to="iso")   # "2026-07-07T14:30:00"
```

### 4. Humanize a past event

```python
from chronos import Time

t = Time(options={"BASE_TIME": "2026-07-01 12:00"})
print(t.humanize(against="2026-07-01 11:30"))  # "30 minutes ago"
```

### 5. Generate a safe filename

```python
from chronos.utils import Utils

u = Utils()
filename = f"backup_{u.timestamp_slug()}.sql"
```

---

## Contributing

Contributions are welcome! Please open an issue or pull request on [GitHub](https://github.com/DevPedroLab/chronos). Ensure code is well‑tested and follows the existing style.

---

## License

Chronos is released under the MIT License. See [LICENSE](LICENSE) for details.

---

**Made with ❤️ by [DevPedroLab](https://github.com/DevPedroLab)**
