Skip to content

Instantly share code, notes, and snippets.

@wkettler
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkettler/9238835 to your computer and use it in GitHub Desktop.
Save wkettler/9238835 to your computer and use it in GitHub Desktop.
import re
def to_units(value, unit):
"""
Convert a size string from unit x to unit y.
Input:
value (str): Size string
unit (str): Unit to convert to
Output:
r_value (str): Size string
"""
units = [ 'B', 'K', 'M', 'G', 'T', 'P', 'E' ]
# Confirm provided unit is supported
unit = unit.upper()
if unit not in units:
raise ValueError('invalid unit %s' % unit)
# Match any floating point number followed by an optional unit
m = re.search(r'^([0-9]*\.?[0-9]+)([%s])?b?$' % ''.join(units), value, re.IGNORECASE)
if not m:
raise ValueError('invalid format %s' % value)
v_num = float(m.group(1))
if m.group(2):
v_unit = m.group(2).upper()
else:
v_unit = 'B'
# Perform byte calculation
v_byte = v_num * 1024 ** units.index(v_unit)
# Perform byte to string conversion
r_num = v_byte / 1024 ** units.index(unit)
r_value = '%s%sB' % ("{0:.2f}".format(r_num), unit)
return r_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment