Python pint module - Units conversion utility

Python pint module

  • pint module allows arithmetic operations between numerical values and conversions from and to different units.
  • Makes unit conversion easy.
  • pint has a complete test coverage, runs in Python 2.7 and 3.3+ with no other dependency, and licensed under BSD.

How to install pint module?

In fedora/centos/rhel,
$ sudo pip install pint
When running above command
Collecting pint
  Downloading (162kB)
    100% |████████████████████████████████| 163kB 973kB/s 
Installing collected packages: pint
  Running install for pint ... done
Successfully installed pint-0.8.1

How to consume pint module in python program?

import pint
Create instance for pint UnitRegistry
define units using define instance method for all the required units.
UNIT_CONVERTER.define('MB = 1024 KB')

Python program to convert memory size to KB from different units

This python program is used to convert memory size value to KB unit from MB, and GB.


import pint

UNIT_CONVERTER = pint.UnitRegistry(filename=None)
UNIT_CONVERTER.define('kB = []')
UNIT_CONVERTER.define('KB = []')
UNIT_CONVERTER.define('MB = 1024 KB')
UNIT_CONVERTER.define('GB = 1048576 KB')

def convert_memory_unit_in_kb(mem_val):
    memory_kb = int(UNIT_CONVERTER(mem_val).to_base_units())
    return memory_kb

if __name__ == '__main__':
    mem_val = input("Enter memory size:");
    mem_size_kb = convert_memory_unit_in_kb(mem_val)
    print('Memory size in KB:' + str(mem_size_kb));
$ python 
Enter memory size:'343434 MB'
Memory size in KB:351676416

$ python 
Enter memory size:'2242424MB'
Memory size in KB:2296242176

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter