Back to Blog
Python

Using Python Humanize: naturaltime, naturaldate, and intcomma

python humanize naturaltime naturaldate and intcomma: Learn how to use Python's humanize library to format relative times, dates, and numbers with naturaltime, natural...

humanizedatetime formattingnumber formattinglocalizationpython utilities
A clock and a number with commas representing humanize's naturaltime, naturaldate, and intcomma formatting in Python.

python humanize naturaltime naturaldate and intcomma requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

When you need to display timestamps or large numbers in a way that people actually read, the humanize library is a straightforward choice. The functions naturaltime, naturaldate, and intcomma cover three common formatting needs: relative time, calendar dates, and numeric grouping. This article focuses on how to use these functions correctly, what their output looks like, and where their behavior can surprise you.

Installing and Importing humanize

The humanize package is available on PyPI and installs with pip:

pip install humanize

Once installed, import the functions you need directly:

from humanize import naturaltime, naturaldate, intcomma

All three functions work with Python 3 and are pure Python, so they integrate easily into web applications, CLI tools, or data pipelines. The examples below assume a recent version of the library; behavior for edge cases may vary slightly across versions, so check the library's changelog if you depend on a specific output format.

Using naturaltime for Relative Time

naturaltime converts a datetime, date, timedelta, or numeric timestamp into a human-friendly relative phrase. The most common use is showing when an event occurred relative to now.

from datetime import datetime, timedelta from humanize import naturaltime now = datetime.now() print(naturaltime(now - timedelta(seconds=5))) # "5 seconds ago" print(naturaltime(now - timedelta(days=2))) # "2 days ago" print(naturaltime(now + timedelta(hours=3))) # "3 hours from now" print(naturaltime(now)) # "now"

The function automatically decides between past and future phrasing. For a timedelta, it interprets the delta relative to the current time, so a negative delta yields a past phrase and a positive delta yields a future phrase. If you pass a datetime in the past, you get "... ago"; if it's in the future, you get "... from now".

You can also force the direction with the when parameter:

print(naturaltime(now - timedelta(days=1), when='past')) # "a day ago" print(naturaltime(now - timedelta(days=1), when='future')) # "a day from now"

This is useful when you know the semantic context and want to avoid ambiguity, for example when displaying a countdown that should always read as future even if the timestamp is slightly off.

Using naturaldate for Human-Readable Dates

naturaldate formats a date or datetime as a concise calendar date. It uses the current date as a reference and returns special phrases for today, yesterday, and tomorrow.

from datetime import date, timedelta from humanize import naturaldate today = date.today() print(naturaldate(today)) # "today" print(naturaldate(today - timedelta(days=1))) # "yesterday" print(naturaldate(today + timedelta(days=1))) # "tomorrow" print(naturaldate(today + timedelta(days=10))) # "Oct 20 2025" (example)

For dates further away, it falls back to a month-day-year format. The exact format depends on the locale and the library version, but it typically follows the %b %d %Y pattern, for example "Jan 5 2026".

Unlike naturaltime, naturaldate does not include the time of day. If you pass a datetime, it ignores the time component and only considers the date. This makes it suitable for showing deadlines, birthdays, or any calendar event where the time is irrelevant.

Using intcomma for Number Formatting

intcomma inserts thousands separators into integers and floats. For floats, it separates the integer part and leaves the fractional part unchanged.

from humanize import intcomma print(intcomma(1234567)) # "1,234,567" print(intcomma(1234567.891)) # "1,234,567.891" print(intcomma(-1000000)) # "-1,000,000" print(intcomma(100)) # "100"

The function works with both int and float types, and also with strings that represent numbers. For strings, it parses the numeric part and inserts commas appropriately:

print(intcomma("1234567")) # "1,234,567" print(intcomma("1234567.89")) # "1,234,567.89"

If you pass a string that is not a valid number, it raises a ValueError. This is worth keeping in mind when processing user input or data from external sources.

Combining These Functions in Realistic Output

In practice, you rarely use these functions in isolation. A typical use case is generating a human-readable activity feed or a dashboard that shows both relative time and formatted numbers.

from datetime import datetime, timedelta from humanize import naturaltime, naturaldate, intcomma last_seen = datetime.now() - timedelta(hours=5) file_size = 8451234 print(f"Last seen: {naturaltime(last_seen)}") print(f"File size: {intcomma(file_size)} bytes") print(f"Report date: {naturaldate(last_seen.date())}")

Output:

Last seen: 5 hours ago File size: 8,451,234 bytes Report date: today

Because these functions return plain strings, you can embed them in templates, log messages, or API responses without extra formatting logic.

Localization and Language Support

The humanize library supports multiple locales. By default, it uses English, but you can activate a different locale to get localized output for all three functions.

import humanize from datetime import datetime, timedelta humanize.activate("fr_FR") now = datetime.now() print(humanize.naturaltime(now - timedelta(days=1))) # "il y a 1 jour" print(humanize.intcomma(1234567)) # "1 234 567" (space separator)

Not every locale is fully translated, and the separator for intcomma varies by locale (comma, period, or space). If your application targets multiple regions, test the output for each locale you support. Also note that activate changes the global locale, so in a multi-threaded web server you need to manage locale per request or use the locale parameter if available in your version.

Performance and Formatting Considerations

These functions are lightweight and perform well for typical UI rendering. naturaltime and naturaldate do a small amount of date arithmetic and string formatting, while intcomma does a regex-based insertion. None of them involve I/O or heavy computation, so they are safe to call in request handlers or loops that process thousands of items.

One thing to keep in mind is that naturaltime and naturaldate depend on the current time. If you call them repeatedly in a loop, they will use the same datetime.now() internally, but the result may become stale if the loop runs for a long time. For a live dashboard, consider computing the reference time once and passing it explicitly if your library version supports a reference parameter. Otherwise, be aware that the output is relative to the moment the function is called.

Another consideration is that the output format is not meant to be parsed programmatically. If you need to store or compare these strings, keep the original timestamp or number separately. The humanized version is for display only.

Edge Cases and Behavior with Different Input Types

All three functions accept multiple input types, but the behavior can differ in subtle ways.

naturaltime accepts datetime, date, timedelta, and numeric timestamps (Unix time). For a numeric timestamp, it interprets the value as seconds since the epoch. Passing a date object works, but it treats the date as midnight, so the relative time will be based on that instant.

naturaldate only cares about the calendar date. If you pass a datetime, it ignores the time part. If you pass a timedelta, it treats it as a relative offset from today, so naturaldate(timedelta(days=2)) returns the date two days from now.

intcomma handles negative numbers and floats correctly, but it does not handle scientific notation or strings with leading/trailing whitespace. If you pass a string like " 1234 ", it raises a ValueError because the whitespace prevents parsing. You can strip the string first if needed.

These edge cases are not bugs; they are the result of the library's design to keep the API simple. When you know the exact type you are passing, the behavior is predictable. When you are unsure, convert to a known type before calling the function.

For most applications, naturaltime, naturaldate, and intcomma give you exactly the formatting you need without writing custom date and number formatting code. They are small, focused utilities that make output friendlier while keeping your codebase clean.

python humanize naturaltime naturaldate and intcomma: Practi | RYUSLOG DEV