Python Programming 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 https://files.pythonhosted.org/packages/1e/40/6938f7d544eef208a8183c2c80624289e8a4f4e0aea43f4658b9527077de/Pint-0.8.1.tar.gz (162kB)
    100% |████████████████████████████████| 163kB 973kB/s 
Installing collected packages: pint
  Running setup.py 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
pint.UnitRegistry(filename=None)
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.

#!/usr/bin/python

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));
Output:
$ python memory-unit-converter-pint.py 
Enter memory size:'343434 MB'
Memory size in KB:351676416

$ python memory-unit-converter-pint.py 
Enter memory size:'2242424MB'
Memory size in KB:2296242176

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^