python django 将byte 转换成MB,GB

将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)

# 若用户传递的是 56MB
num = 56  # 数值
unit = 'MB'  # 单位
b = get_file_size_unit('MB')
print(b)  # 1000000  
# 最后的byte:
print(num * b)  # 56000000  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值