humanreadable
humanreadable is a Python library to convert human-readable values for sizes, times, and bit rates into other units. It supports various formats like '1MB', '1 day', or '100Mbps'. The current version is 0.4.1. Releases occur irregularly, often tied to Python version support updates and essential bug fixes.
Common errors
-
ImportError: cannot import name 'Size' from 'humanreadable'
cause The class name 'Size', 'Time', 'BitPerSecond', or 'BitsPerSecond' is misspelled, or the library is not correctly installed.fixVerify installation with `pip list | grep humanreadable`. Ensure class names are capitalized correctly (e.g., `Size` not `size`). -
TypeError: 'int' object is not iterable
cause This error can occur if code written for `humanreadable<0.2.0` (where `BitPerSecond.bps` was `int`) is run with `humanreadable>=0.2.0` (where `BitPerSecond.bps` is `float`), and the code performs `int`-specific operations.fixAdapt your code to expect and handle `float` values from `BitPerSecond.bps`, or explicitly cast to `int` if necessary (e.g., `int(rate.bps)`). -
AttributeError: 'Time' object has no attribute 'to_humanreadable'
cause Attempting to use the `to_humanreadable` method on a `Time` object with a version of the library prior to its introduction.fixThe `to_humanreadable` method for `Time` was added in v0.3.0. Upgrade your `humanreadable` library to version 0.3.0 or higher.
Warnings
- breaking Python version support has been dropped for older interpreters. Specifically, v0.4.1 dropped support for Python 3.8/3.9, v0.4.0 dropped 3.6, and v0.2.0 dropped 3.5.
- breaking The `BitPerSecond.bps` property type changed from `int` to `float`.
- gotcha The `to_humanreadable` method for the `Time` class could fail when the value represented more than one day.
Install
-
pip install humanreadable
Imports
- Size
from humanreadable import Size
- Time
from humanreadable import Time
- BitPerSecond
from humanreadable import BitPerSecond
- BitsPerSecond
from humanreadable import BitsPerSecond
Quickstart
from humanreadable import Size, Time, BitsPerSecond
# Convert human-readable size to bytes, kilobytes, etc.
size_mb = Size("1.5 MB")
print(f"1.5 MB is {size_mb.byte} bytes")
print(f"1.5 MB is {size_mb.kbyte} KB")
# Convert human-readable time to seconds, minutes, hours, etc.
time_day = Time("2 days 3 hours")
print(f"2 days 3 hours is {time_day.hours} hours")
print(f"2 days 3 hours is {time_day.minutes} minutes")
# Convert human-readable bit rate to bits per second, kilobits per second, etc.
rate_gbps = BitsPerSecond("10 Gbps")
print(f"10 Gbps is {rate_gbps.bps} bits/second")
print(f"10 Gbps is {rate_gbps.giga_bps} Gbps")
# Perform arithmetic operations (available from v0.3.0+)
size_a = Size("10 MB")
size_b = Size("2048 KB") # 2MB
total_size = size_a + size_b
print(f"10 MB + 2048 KB = {total_size.mbyte} MB")