Skip to content

Instantly share code, notes, and snippets.

@shawnbutts
Created October 17, 2012 17:33
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save shawnbutts/3906915 to your computer and use it in GitHub Desktop.
Save shawnbutts/3906915 to your computer and use it in GitHub Desktop.
bytes to to mb, gb, etc in python
def bytesto(bytes, to, bsize=1024):
"""convert bytes to megabytes, etc.
sample code:
print('mb= ' + str(bytesto(314575262000000, 'm')))
sample output:
mb= 300002347.946
"""
a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
r = float(bytes)
for i in range(a[to]):
r = r / bsize
return(r)
Copy link

ghost commented Mar 2, 2018

when i use the function of sys.getsizeof() , how to Convert into mb, gb, etc .
thanks

@navercm418
Copy link

Nice job. i use this along with psutil for sys admin reports

@mtovmassian
Copy link

mtovmassian commented Jul 23, 2020

Thank you, it helped me a lot to clear my mind.
I just got rid of the for-loop like so:

def bytesto(bytes, to, bsize=1024): 
    a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
    r = float(bytes)
    return bytes / (bsize ** a[to])

@Intelrunner
Copy link

Thank you. I needed this for a quick customer op.

@Srija-ravi
Copy link

thanks , very help full , need to change the bytes to days
1.4492465e+07 to day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment