Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Humanize: Format File Sizes, Numbers, and Times

Learn to use the Python humanize library to turn raw bytes, large numbers, and timestamps into readable strings like 1.5 MB, 1.2 million, and 2 hours ago.

~4 min readPython
#humanize#python-formatting#datetime#file-size
Illustration of a Python script converting raw byte counts, large integers, and timestamps into readable labels such as 1.5 MB, 1.2 million, and 2 hours ago.

The humanize package converts raw byte counts, large integers, and timestamps into strings that people can read at a glance. For example, 1536000 can become 1.5 MB, 1200000 can become 1.2 million, and a timestamp can become 2 hours ago. This article shows how to install and use humanize for file sizes, numbers, and times, and where its defaults matter.

Installing humanize and Importing the Functions

humanize is a small library focused on human-readable formatting. Install it with pip:

bash
pip install humanize

Import the module:

python
import humanize

You can also import individual functions, for example from humanize import naturalsize, intword, and call them without the humanize. prefix. The examples below use the full humanize. prefix for clarity. The formatting helpers take a numeric or datetime value and return a string, so they are easy to call from display code. Relative-time helpers depend on the current time, so their output naturally changes over time.

Formatting File Sizes With naturalsize

naturalsize converts a byte count into a unit-labeled string:

python
humanize.naturalsize(1536000) # '1.5 MB' humanize.naturalsize(1000) # '1.0 kB' humanize.naturalsize(0) # '0 bytes'

The default behavior uses base 1000, matching the SI convention where 1 kB is 1000 bytes. Storage vendors and network tools commonly use this convention. If your application measures memory or disk in binary units, pass binary=True:

python
humanize.naturalsize(1536000, binary=True) # '1.5 MiB' humanize.naturalsize(1024, binary=True) # '1.0 KiB'

The gnu=True option produces the short binary form used by GNU tools such as ls -lh:

python
humanize.naturalsize(1536000, gnu=True) # '1.5M'

You can control the number of decimals with the format argument:

python
humanize.naturalsize(1536000, format='%.2f') # '1.54 MB'

Negative values keep their sign: naturalsize(-2048) returns -2.0 kB. The singular form 1 byte is used for exactly one byte, and zero is reported as 0 bytes.

Formatting Large Numbers With intword and intcomma

For counts, totals, and metrics, intword turns large integers into words:

python
humanize.intword(1200000) # '1.2 million' humanize.intword(1500000000) # '1.5 billion' humanize.intword(-2500000) # '-2.5 million'

intcomma inserts thousands separators without changing the value:

python
humanize.intcomma(1234567) # '1,234,567' humanize.intcomma(9876543.21) # '9,876,543.21'

Use intcomma when the exact value matters and the number is small enough to read with separators. Use intword when the magnitude is the point of the display, such as 1.2 million downloads. For ordinal positions, ordinal appends the correct suffix:

python
humanize.ordinal(1) # '1st' humanize.ordinal(23) # '23rd' humanize.ordinal(112) # '112th'

Formatting Times and Dates With naturaltime

naturaltime converts a datetime or timedelta into a relative phrase:

python
from datetime import datetime, timedelta past = datetime.now() - timedelta(hours=2) future = datetime.now() + timedelta(days=3) humanize.naturaltime(past) # '2 hours ago' humanize.naturaltime(future) # '3 days from now'

Recent values collapse to now. The exact threshold and phrasing can vary between releases, so pin the version you test against and assert expected output in tests.

naturalday adds the labels today, yesterday, and tomorrow when the date is nearby:

python
humanize.naturalday(datetime.now()) # 'today' humanize.naturalday(datetime.now() - timedelta(days=1)) # 'yesterday'

naturaldate is a companion for when you need a formatted date instead of a relative phrase; its exact format depends on the current date and locale.

Timezone handling matters. When you pass a naive datetime, the formatting is relative to local system time. When you pass a timezone-aware datetime, the library uses the value's timezone to compare with the current time. To avoid surprising offsets, normalize all timestamps to one convention before calling naturaltime.

Using precisedelta for Exact Durations

naturaltime is for relative moments. For exact durations, precisedelta breaks a timedelta into components:

python
humanize.precisedelta(timedelta(hours=1, minutes=2, seconds=3)) # '1 hour, 2 minutes and 3 seconds'

The minimum_unit argument controls the smallest unit shown:

python
humanize.precisedelta(timedelta(minutes=5, seconds=45), minimum_unit='minutes') # '5 minutes'

This is useful for logs, job runtimes, and ETL reporting where a rounded relative phrase is not specific enough.

Combining Formatting Functions in an Output Layer

The functions compose cleanly. A file listing view can format size, count, and modification time in one place:

python
from datetime import datetime def describe_file(path): stat = path.stat() return { 'size': humanize.naturalsize(stat.st_size, binary=True), 'modified': humanize.naturaltime(datetime.fromtimestamp(stat.st_mtime)), } def describe_directory(path): entries = list(path.iterdir()) total = sum(e.stat().st_size for e in entries) return { 'items': humanize.intword(len(entries)), 'total_size': humanize.naturalsize(total, binary=True), }

Keeping display formatting in one module means the same unit conventions and timezone rules apply everywhere. If the product later switches from binary to decimal file sizes, the change happens in one function instead of across every template or API response.

Performance and Maintainability Considerations

The formatting conversions are small arithmetic and string operations. For a list of a few thousand rows, the cost is negligible compared to the I/O that produced the data. If you are formatting millions of values, precompute the formatted strings once and reuse them instead of calling the functions repeatedly inside a hot loop.

Localization is the main operational consideration. humanize ships locale files, and activating a locale has a one-time loading cost. If your application serves multiple languages, load the locale once at startup and keep the formatted output in the presentation layer, not in persisted data. Storing formatted strings in a database makes later re-formatting or locale changes impossible without a migration.

The largest compatibility risk is version drift. The exact wording of unit labels can differ between releases, and relative-time behavior can change. Add a test that asserts the output for a fixed input, such as naturalsize(1024, binary=True) == '1.0 KiB', so an upgrade that changes wording fails loudly instead of silently altering every page.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.