Skip to content

Instantly share code, notes, and snippets.

@ultrafunkamsterdam
Last active August 26, 2022 21:19
Show Gist options
  • Save ultrafunkamsterdam/512c0d6cef59118c094548579cf1f254 to your computer and use it in GitHub Desktop.
Save ultrafunkamsterdam/512c0d6cef59118c094548579cf1f254 to your computer and use it in GitHub Desktop.
bytes / kb / mb / gb / tb / etc unit converter
# BY ULTRAFUNKAMSTERDAM
# https://github.com/ultrafunkamsterdam
"""
███████ ██ ███ ███ ██████ ██ ███████ ███████ ████████ ██ ██ ███████ ███████
██ ██ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██ ██ ████ ██ ██████ ██ █████ ███████ ██ ██ ██ █████ █████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██ ██ ██ ██ ███████ ███████ ███████ ██ ██████ ██ ██
_ _ _ _ _ _
| |__ _ _| |_ ___| |_(_) | |
| '_ \| | | | __| / __| __| | | |
| |_) | |_| | |_ \__ \ |_| | | |
|_.__/ \__,_|\__| |___/\__|_|_|_| _ _
| |__ __ ___ _____ | |_ ___ | | ___ ___ | | __ _ _ _ __
| '_ \ / _` \ \ / / _ \ | __/ _ \ | |/ _ \ / _ \| |/ / | | | | '_ \
| | | | (_| |\ V / __/ | || (_) | | | (_) | (_) | < | |_| | |_) |
|_| |_|\__,_| \_/ \___| \__\___/_ |_|\___/ \___/|_|\_\ \__,_| .__/
_____ _____ _ __ _ _ | |_(_)_ __ ___ ___ |_|
/ _ \ \ / / _ \ '__| | | | | __| | '_ ` _ \ / _ \
| __/\ V / __/ | | |_| | | |_| | | | | | | __/
\___| \_/ \___|_| \__, | \__|_|_| |_|_|_|\___|
_ _ ___ _ _ |___/ ___ ___ __| | (_) |_
| | | |/ _ \| | | | | '_ \ / _ \/ _ \/ _` | | | __|
| |_| | (_) | |_| | | | | | __/ __/ (_| | | | |_
\__, |\___/ \__,_| |_| |_|\___|\___|\__,_| |_|\__|
|___/
"""
def convert_unit( num , src_unit: str = "b" , dst_unit: str = "mb" , human_format = False ):
"""
convert the given <num> from <src_unit> value to <dst_unit> value
possible unit values (lower case also accepted!)
"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
usage
-----
>>> convert_unit(3235432423, "b", "mb")
3085.548804283142
when only dst_unit is provided, we assume the source is bytes
---
>>> convert_unit(13235432423, dst_unit="MB")
3085.548804283142
you can pass the units as positionals as well
---
>>> convert_unit(4, "GB", "MB")
4096
if you want to print a "human friendly string"
---
>>> convert_unit(13235432423, dst_unit="mb", human_format = True)
'12622.29 MB'
"""
src_unit = src_unit.upper()
dst_unit = dst_unit.upper()
unames = ("B" , "KB" , "MB" , "GB" , "TB" , "PB" , "EB" , "ZB" , "YB")
err = None
if src_unit not in unames:
err = "unit from" , src_unit
if dst_unit not in unames:
err = "unit to" , dst_unit
if err:
raise ValueError( "your %s = %s but should be one of %s" % (*err , unames) )
idxfrom = unames.index( src_unit )
idxto = unames.index( dst_unit )
ret = None
if src_unit == dst_unit:
ret = num
if idxfrom < idxto:
ret = num / (1024 ** (idxto - idxfrom))
if idxfrom > idxto:
ret = num * (1024 ** (idxfrom - idxto))
if human_format:
ret = "{0:.2f} {1}".format( ret , dst_unit )
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment