or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-timeago

A very simple python library, used to format datetime with relative time statements like '3 hours ago'.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/timeago@1.0.x

To install, run

npx @tessl/cli install tessl/pypi-timeago@1.0.0

index.mddocs/

Timeago

A very simple Python library for formatting datetime objects into human-readable relative time expressions like "3 hours ago" or "in 2 minutes". Supports 44+ languages and locales with flexible input handling for various datetime formats.

Package Information

  • Package Name: timeago
  • Language: Python
  • Installation: pip install timeago
  • Python Compatibility: 2.5-3.5+
  • Dependencies: None

Core Imports

import timeago

Common usage pattern:

from timeago import format

For parser functions:

import timeago.parser
# or
from timeago import parser

For exceptions:

from timeago.excepts import ParameterUnvalid

Basic Usage

import timeago
from datetime import datetime, timedelta

# Basic usage with current time
date = datetime.now() - timedelta(hours=2)
print(timeago.format(date))  # "2 hours ago"

# Specify reference time and locale
now = datetime.now()
past_time = now - timedelta(minutes=30)
print(timeago.format(past_time, now, 'es'))  # "hace 30 minutos"

# Future time expressions
future_time = now + timedelta(days=3)
print(timeago.format(future_time, now, 'en'))  # "in 3 days"

# Using timedelta directly
delta = timedelta(minutes=15)
print(timeago.format(delta))  # "15 minutes ago"

# String input parsing
print(timeago.format("2016-05-27 21:22:02"))  # relative to current time

Capabilities

Time Formatting

Format datetime objects into relative time expressions supporting both past ("ago") and future ("in") time periods.

def format(date, now=None, locale='en'):
    """
    Format datetime into relative time expression.
    
    Parameters:
    - date: datetime/timedelta/date/time/timestamp/str - Target time to format
    - now: datetime/str/None - Reference time (defaults to current time)  
    - locale: str - Language locale code (defaults to 'en')
    
    Returns:
    str - Formatted relative time string
    
    Raises:
    timeago.excepts.ParameterUnvalid - For invalid input parameters
    """

Input Parsing

Parse various input types into datetime objects for flexible input handling. These functions are available in the timeago.parser module.

# Available as: timeago.parser.parse()
def parse(input):
    """
    Parse various input types to datetime objects.
    
    Parameters:
    - input: datetime/date/time/int/float/str - Input to parse
    
    Returns:
    datetime - Parsed datetime object or None if parsing fails  
    """
# Available as: timeago.parser.date_to_datetime()
def date_to_datetime(d):  
    """
    Convert date object to datetime (time set to 00:00:00).
    
    Parameters:
    - d: date - Date object to convert
    
    Returns:
    datetime - Datetime object
    """
# Available as: timeago.parser.time_to_datetime()
def time_to_datetime(t):
    """
    Convert time object to datetime (using today's date).
    
    Parameters:
    - t: time - Time object to convert
    
    Returns:
    datetime - Datetime object
    """
# Available as: timeago.parser.timestamp_to_datetime()
def timestamp_to_datetime(ts):
    """
    Convert Unix timestamp to datetime object.
    
    Parameters:
    - ts: int/float - Unix timestamp
    
    Returns:
    datetime - Datetime object
    """
# Available as: timeago.parser.string_to_data_time()
def string_to_data_time(d):
    """
    Parse datetime strings in various formats.
    
    Supported formats:
    - "2016-05-27 21:22:02" (standard format)
    - "2016-5-27 21:22:2" (flexible digits)
    - "2016/05/27 21:22:02" (slash separators)
    - "2016-05-27" (date only)
    - "21:22:02" (time only)
    
    Parameters:
    - d: str - Datetime string to parse
    
    Returns:
    datetime - Parsed datetime object or None if parsing fails
    """

Error Handling

Exception class for invalid parameters passed to timeago functions.

class ParameterUnvalid(Exception):
    """
    Exception raised for invalid parameters.
    
    Attributes:
    - value: str - Error message describing the invalid parameter
    """
    
    def __init__(self, value):
        """Initialize with error message."""
    
    def __str__(self):
        """Return string representation of the error."""

Utility Functions

Internal utility functions accessible from the main module.

# Available as: timeago.total_seconds()
def total_seconds(dt):
    """
    Calculate total seconds from a timedelta (Python 2.6 compatibility).
    
    Parameters:
    - dt: timedelta - Timedelta object to convert
    
    Returns:
    float - Total seconds as a float
    """

Locale Support

Access and configuration for internationalization support across 44+ languages.

# Available as: timeago.locales.timeago_template()
def timeago_template(locale, index, ago_in):
    """
    Get localized time expression template.
    
    Parameters:
    - locale: str - Language locale code
    - index: int - Time unit index (0-13: just now, seconds, minutes, hours, days, weeks, months, years)
    - ago_in: int - Time direction (0=past/ago, 1=future/in)
    
    Returns:
    str - Localized time expression template or callable function
    """
# Available as: timeago.locales.locale_module()
def locale_module(mod, locale):
    """
    Extract locale configuration from a locale module.
    
    Parameters:
    - mod: module - The timeago module reference
    - locale: str - Language locale code
    
    Returns:
    list/function - Locale configuration (list of templates or function)
    
    Raises:
    AttributeError - If locale module cannot be loaded
    """

Types

# Built-in Python types used
datetime  # from datetime module
date      # from datetime module  
time      # from datetime module
timedelta # from datetime module
str       # built-in string type
int       # built-in integer type
float     # built-in float type

Constants

# Module metadata
__version__ = '1.0.16'     # Package version
__license__ = 'MIT'        # Package license

# Default settings
DEFAULT_LOCALE = 'en'      # Default language locale

# Internal calculation constants  
SEC_ARRAY = [60.0, 60.0, 24.0, 7.0, 365.0 / 7.0 / 12.0, 12.0]  # Time unit conversion factors
SEC_ARRAY_LEN = 6          # Length of SEC_ARRAY

Supported Locales

The package supports 44+ locales with both past ("ago") and future ("in") expressions:

European Languages: en, en_short, de, fr, es, it, nl, da, fi, sv_SE, nb_NO, nn_NO, pl, pt_BR, pt_PT, ro, bg, el, hu, sk, tr, ru, uk, lt, is, ca, eu, gl

Asian Languages: zh_CN, zh_TW, ja, ko, th, vi, my, ta, ml

Middle Eastern Languages: ar, fa_IR, he

South Asian Languages: in_BG, in_HI, in_ID, guj_IN

Examples

Multiple Input Types

import timeago
import timeago.parser
from datetime import datetime, date, time, timedelta

# Datetime object
dt = datetime(2016, 5, 27, 21, 22, 2)
print(timeago.format(dt))

# Date object (time defaults to 00:00:00)
today = date.today()
print(timeago.format(today))

# Time object (date defaults to today)
current_time = time(15, 30, 45)
print(timeago.format(current_time))

# Timedelta object  
delta = timedelta(hours=1, minutes=30)
print(timeago.format(delta))

# Unix timestamp
timestamp = 1464376922.0
print(timeago.format(timestamp))

# String formats
print(timeago.format("2016-05-27 21:22:02"))
print(timeago.format("2016/5/27 21:22:2"))
print(timeago.format("2016-05-27"))
print(timeago.format("21:22:02"))

# Using parser functions directly
parsed_dt = timeago.parser.parse("2016-05-27 21:22:02")
print(timeago.format(parsed_dt))

# Convert date to datetime explicitly
date_obj = date(2016, 5, 27)
dt_from_date = timeago.parser.date_to_datetime(date_obj)
print(timeago.format(dt_from_date))

Locale Examples

import timeago
from datetime import datetime, timedelta

date = datetime.now() - timedelta(hours=2)

# English (default)
print(timeago.format(date, locale='en'))        # "2 hours ago"

# Spanish
print(timeago.format(date, locale='es'))        # "hace 2 horas"

# French  
print(timeago.format(date, locale='fr'))        # "il y a 2 heures"

# German
print(timeago.format(date, locale='de'))        # "vor 2 Stunden"

# Chinese (Simplified)
print(timeago.format(date, locale='zh_CN'))     # "2小时前"

# Japanese
print(timeago.format(date, locale='ja'))        # "2時間前"

# Arabic
print(timeago.format(date, locale='ar'))        # "منذ ساعتين"

Error Handling

import timeago
from timeago.excepts import ParameterUnvalid

try:
    # Invalid date string
    result = timeago.format("invalid-date-string")
except ParameterUnvalid as e:
    print(f"Error: {e}")

try:
    # Malformed date string
    result = timeago.format("2016-05-27  12:23:23")  # double space
except ParameterUnvalid as e:
    print(f"Error: {e}")