Python --- 常用自定义函数
1. 数值转天时分
# 时间格式转换
def time_format_conversion(seconds):
"""
用于将运行时间等两个时间之间的时间戳之差(单位秒)转换成XX小时XX分钟XX秒的格式
"""
onedays = 24 * 3600
days, other = divmod(seconds, onedays)
hour, other = divmod(other, 3600)
minute, second = divmod(other, 60)
try:
if days:
return f"{int(days)}天 {int(hour)}:{int(minute)}:{int(second)}"
else:
return f"{int(hour)}:{int(minute)}:{int(second)}"
except Exception:
if days:
return f"{days}天 {hour}:{minute}:{second}"
else:
return f"{hour}:{minute}:{second}"
2. 将 datetime 转成本地时区时间
from django.utils import timezone
# 获取本地时区
tz = timezone.get_current_timezone()
# 将datetime对象转成本地时区时间
previous_closed_time= timezone.localtime(obj.status_source.previous_closed_time,tz)
# 格式化时间
previous_closed_time = datetime.strftime(previous_closed_time,"%Y-%m-%d %H:%M:%S")
3. 文件大小单位转换
def byteConverter(size, dot=2):
size = float(size)
# 位 比特 bit
if 0 <= size < 1:
human_size = str(round(size / 0.125, dot)) + 'b'
# 字节 字节 Byte
elif 1 <= size < 1024:
human_size = str(round(size, dot)) + 'B'
# 千字节 千字节 Kilo Byte
elif math.pow(1024, 1) <= size < math.pow(1024, 2):
human_size = str(round(size / math.pow(1024, 1), dot)) + 'KB'
# 兆字节 兆 Mega Byte
elif math.pow(1024, 2) <= size < math.pow(1024, 3):
human_size = str(round(size / math.pow(1024, 2), dot)) + 'MB'
# 吉字节 吉 Giga Byte
elif math.pow(1024, 3) <= size < math.pow(1024, 4):
human_size = str(round(size / math.pow(1024, 3), dot)) + 'GB'
# 太字节 太 Tera Byte
elif math.pow(1024, 4) <= size < math.pow(1024, 5):
human_size = str(round(size / math.pow(1024, 4), dot)) + 'TB'
# 拍字节 拍 Peta Byte
elif math.pow(1024, 5) <= size < math.pow(1024, 6):
human_size = str(round(size / math.pow(1024, 5), dot)) + 'PB'
# 艾字节 艾 Exa Byte
elif math.pow(1024, 6) <= size < math.pow(1024, 7):
human_size = str(round(size / math.pow(1024, 6), dot)) + 'EB'
# 泽它字节 泽 Zetta Byte
elif math.pow(1024, 7) <= size < math.pow(1024, 8):
human_size = str(round(size / math.pow(1024, 7), dot)) + 'ZB'
# 尧它字节 尧 Yotta Byte
elif math.pow(1024, 8) <= size < math.pow(1024, 9):
human_size = str(round(size / math.pow(1024, 8), dot)) + 'YB'
# 千亿亿亿字节 Bront Byte
elif math.pow(1024, 9) <= size < math.pow(1024, 10):
human_size = str(round(size / math.pow(1024, 9), dot)) + 'BB'
# 百万亿亿亿字节 Dogga Byte
elif math.pow(1024, 10) <= size < math.pow(1024, 11):
human_size = str(round(size / math.pow(1024, 10), dot)) + 'NB'
# 十亿亿亿亿字节 Dogga Byte
elif math.pow(1024, 11) <= size < math.pow(1024, 12):
human_size = str(round(size / math.pow(1024, 11), dot)) + 'DB'
# 万亿亿亿亿字节 Corydon Byte
elif math.pow(1024, 12) <= size:
human_size = str(round(size / math.pow(1024, 12), dot)) + 'CB'
# 负数
else:
raise ValueError('{}() takes number than or equal to 0, but less than 0 given.'.format(pybyte.__name__))
return human_size
python防脱发技巧

浙公网安备 33010602011771号