Timeago (Python)
A very simple Python library, used to format datetime with a "*** time ago" statement, e.g., "3 hours ago". The current version is 1.0.16. The project has a slower release cadence, with the last release in August 2022, but it is actively maintained.
Warnings
- gotcha The library is designed for human-readable approximations (e.g., '3 minutes ago') rather than precise duration reporting. If exact time differences like '1 month 19 days ago' are required, consider libraries such as `dateutil.relativedelta` instead.
- gotcha Users must handle timezone awareness consistently when providing `datetime` objects to `timeago.format()`. Mixing timezone-naive and timezone-aware datetimes can lead to unexpected results. Note that `datetime.datetime.utcnow()` is deprecated in Python 3.12+; the recommended approach for UTC is `datetime.datetime.now(datetime.UTC)`.
- gotcha When bundling applications with PyInstaller, `timeago`'s locale files might not be automatically included, leading to `ModuleNotFoundError` for locales.
Install
-
pip install timeago
Imports
- format
import timeago timeago.format(...)
Quickstart
import timeago
import datetime
# Get current time for comparison
now = datetime.datetime.now()
# Example 1: Past datetime
past_date = datetime.datetime.now() - datetime.timedelta(days=2, hours=3, minutes=30)
print(f"Past date: {timeago.format(past_date, now)}")
# Example 2: Future datetime (relative to now)
future_date = datetime.datetime.now() + datetime.timedelta(hours=5)
print(f"Future date: {timeago.format(future_date, now)}")
# Example 3: Using a timedelta directly
time_delta_example = datetime.timedelta(seconds=60 * 3.4)
print(f"Timedelta: {timeago.format(time_delta_example)}")
# Example 4: With a specific locale (e.g., Chinese Simplified)
# Ensure your system supports UTF-8 for printing non-ASCII characters
print(f"Locale example (zh_CN): {timeago.format(past_date, now, 'zh_CN')}")