Skip to main content

A Python library for quickly manipulating time and obtain time data.

Project description

Chronos Timetool

A Swiss Army knife for time manipulation in Python.

Python Version Version License Maintained

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

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 helpersnext_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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chronos_timetool-0.1.0.tar.gz (23.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chronos_timetool-0.1.0-py3-none-any.whl (26.4 kB view details)

Uploaded Python 3

File details

Details for the file chronos_timetool-0.1.0.tar.gz.

File metadata

  • Download URL: chronos_timetool-0.1.0.tar.gz
  • Upload date:
  • Size: 23.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.1

File hashes

Hashes for chronos_timetool-0.1.0.tar.gz
Algorithm Hash digest
SHA256 054839652390b7d22423b3ed9bda2ea318a06b82455ae14ee2a8dd56057122a3
MD5 c46bcfa17f6bc7bcd680d234c4b29477
BLAKE2b-256 994192f3d1069050a3dba7f4681d0c031115c6a9ff4e3cfc425b893d9acfaa48

See more details on using hashes here.

File details

Details for the file chronos_timetool-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for chronos_timetool-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9ebac6e0e45785721e0fb5ec9a020e6a4f1d6ce73ae225c2380e1110ac404072
MD5 84d0e9446bcc9ae3f51da0c81a91501d
BLAKE2b-256 611836337adeecc3453d818d07a5895142205262f6004ff92924681e92ee95f2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page