Skip to main content

Chronos Timetool

A Swiss Army knife for time manipulation in Python.

Python Version Version License Maintained Downloads

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

  • ⏱️ 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

pip install chronos-timetool

Chronos requires Python 3.9+ 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.

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.

@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.

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.

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.

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

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)
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.

# 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.

# 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.

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.

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.

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.

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).

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

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

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

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

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

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. Ensure code is well‑tested and follows the existing style.


License

Chronos is released under the MIT License. See LICENSE for details.


Made with ❤️ by DevPedroLab

Metadata

Release files for chronos-timetool 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for chronos-timetool 0.1.2
File Size Uploaded
chronos_timetool-0.1.2.tar.gz 23.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for chronos-timetool 0.1.2
File Interpreter ABI Platform
chronos_timetool-0.1.2-py3-none-any.whl Python 3 none any Details

Total release size: 50.1 kB

Release files / chronos_timetool-0.1.2.tar.gz

Download URL chronos_timetool-0.1.2.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
70e3bf7ffcbe1fb4d85cfcd6bba4dea8d939a73440f50931ec79adaa1d3e242e
BLAKE2b-256 checksum
How to use checksums
e8075aa9fd1eb7a08a5926cf4220d13ef0c918a59229d1394f3bdd91446fd940
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.1

Release files / chronos_timetool-0.1.2-py3-none-any.whl

Download URL chronos_timetool-0.1.2-py3-none-any.whl
Size 26.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ef606fffe2ee2157e8b65a80320b4b1c10b5f59cf300e27118025afcaa7c63e9
BLAKE2b-256 checksum
How to use checksums
41e5f302f4c69ebee6f09b56fd76a7e56205abfa3d10129e7e7257fbac4a0806
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.1

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page