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.

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:
pip install humanizeImport the module:
import humanizeYou 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:
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:
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:
humanize.naturalsize(1536000, gnu=True) # '1.5M'You can control the number of decimals with the format argument:
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:
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:
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:
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:
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:
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:
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:
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:
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 toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.