将byte 转换成MB,GB
from django.template.defaultfilters import filesizeformat
total = 1077772160 # 单位是byte
s = filesizeformat(total)
print(s) # 1.0GB
total = 829145600 # 单位是byte
s = filesizeformat(total)
print(s) # 890MB
根据MB,GB转换成byte
UNIT_KB = 'kb'
UNIT_MB = 'mb'
UNIT_GB = 'gb'
UNIT_TB = 'tb'
UNIT_PB = 'pb'
UNIT_KIB = 'kib'
UNIT_MIB = 'mib'
UNIT_GIB = 'gib'
UNIT_TIB = 'tib'
UNIT_PIB = 'pib'
def get_file_size_unit(unit_type):
table = {
# decimal
UNIT_KB: 10 ** 3,
UNIT_MB: 10 ** 6,
UNIT_GB: 10 ** 9,
UNIT_TB: 10 ** 12,
UNIT_PB: 10 ** 15,
# binary
UNIT_KIB: 1 << 10,
UNIT_MIB: 1 << 20,
UNIT_GIB: 1 << 30,
UNIT_TIB: 1 << 40,
UNIT_PIB: 1 << 50,
}
unit_type = unit_type.lower()
if unit_type not in table.keys():
raise TypeError('Invalid unit type')
return table.get(unit_type)
s = get_file_size_unit('MB')
print(s) # 1000000