Humanize Package in Python

Humanize Package in Python

The humanize package in Python is a very useful tool for making data more human-readable. It's commonly used for formatting numbers, dates, and file sizes in a way that is easier for people to understand. Here's an overview of some of the key features and functionalities of the humanize package:

Installation

First, you need to install the package using pip:

pip install humanize 

Features

  1. Number Formatting:

    • Integers: Convert large numbers into a human-readable format, like turning 1234567 into 1.2 million.
    • Floating-Point Numbers: Format floating-point numbers for readability, such as converting 0.1234567 to 0.123.
    import humanize print(humanize.intword(1234567)) # Output: '1.2 million' print(humanize.intcomma(1234567)) # Output: '1,234,567' print(humanize.naturalsize(123456789)) # Output: '117.7 MB' (assuming file size) 
  2. Date and Time Formatting:

    • Natural Time: Convert time differences into a friendly time, like "3 days ago" or "in two hours".
    import datetime from humanize import naturaltime delta = datetime.timedelta(days=3) past = datetime.datetime.now() - delta future = datetime.datetime.now() + delta print(naturaltime(past)) # Output: '3 days ago' print(naturaltime(future)) # Output: 'in 3 days' 
  3. File Size Formatting:

    • Format file sizes in a human-readable format, e.g., converting 12345678 bytes into 11.8 MB.
    print(humanize.naturalsize(12345678)) # Output: '11.8 MB' 
  4. Ordinal Formatting:

    • Convert numbers into their ordinal representations, like 1 to 1st, 2 to 2nd, etc.
    print(humanize.ordinal(1)) # Output: '1st' print(humanize.ordinal(2)) # Output: '2nd' 
  5. Fractional Formatting:

    • Useful for representing fractions in a more readable way.
    print(humanize.fractional(1/3)) # Output: '1/3' 

Use Cases

  • User Interfaces: Improving the readability of numbers, dates, and file sizes in applications.
  • Data Reporting: Making reports more understandable by formatting large numbers and dates.
  • Logging: Humanizing time stamps in logs for better readability.

Conclusion

The humanize package is a powerful tool for making numerical and time data more readable. It's especially useful in user interfaces and data reports where readability is a key concern. The simplicity of its functions makes it easy to integrate into Python projects.


More Tags

uitableview laravel-passport autoload mediatr oracle-manageddataaccess oracle12c bots mule-el lwc datetime-parsing

More Programming Guides

Other Guides

More Programming Examples