A Python library for quickly manipulating time and obtain time data.
Project description
Chronos Timetool
A Swiss Army knife for time manipulation in Python.
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
- Installation
- Core Module (
core.py) - Parser Module (
parser.py) - Utils Module (
utils.py) - Packages & Exceptions
- Examples
- Contributing
- 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
pip install chronos-timetool
Chronos requires Python 3.9+ and depends on:
babel– for locale‑aware formattingpython-dateutil– for flexible parsingpytz– for timezone handlingcountryinfo– for offline country dataparsedatetime– 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 floatFORMAT– locale string (e.g.,"pt-BR")LOCAL– boolean; ifTrue, uses local system timezoneAM_PM– boolean;Truefor 12‑hour displayBASE_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 fromBASE_TIMEto 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
datetimeobjects - 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 adatetimeobject"posix"– returns Unix timestamp (float)"iso"– returns ISO 8601 string"dict"– returns dictionary withyear,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 aToolsclass with rounding, type checking, and limit functions.exceptions.py– custom exceptions for clear error handling:ParserErrorExceptionHumanizerErrorExceptionCountryCodeNotFoundExceptionIsLeapYearValueErrorExceptionTimestampSlugValueErrorException
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file chronos_timetool-0.1.2.tar.gz.
File metadata
- Download URL: chronos_timetool-0.1.2.tar.gz
- Upload date:
- Size: 23.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
70e3bf7ffcbe1fb4d85cfcd6bba4dea8d939a73440f50931ec79adaa1d3e242e
|
|
| MD5 |
786374f5ddd7b57251da2b9df86e8242
|
|
| BLAKE2b-256 |
e8075aa9fd1eb7a08a5926cf4220d13ef0c918a59229d1394f3bdd91446fd940
|
File details
Details for the file chronos_timetool-0.1.2-py3-none-any.whl.
File metadata
- Download URL: chronos_timetool-0.1.2-py3-none-any.whl
- Upload date:
- Size: 26.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ef606fffe2ee2157e8b65a80320b4b1c10b5f59cf300e27118025afcaa7c63e9
|
|
| MD5 |
180bd8419e8e3b8fefdc848c75e77a28
|
|
| BLAKE2b-256 |
41e5f302f4c69ebee6f09b56fd76a7e56205abfa3d10129e7e7257fbac4a0806
|