Python数字时钟分钟/秒为0补前导0的实现优化咨询
Python数字时钟前导零补全优化方案
核心优化思路
- 无需额外编写if判断实现补零逻辑,直接使用Python内置的字符串格式化能力,即可实现数值不足2位时自动补前导零
- 抽离重复的输出逻辑,不需要在每个时间判断分支中重复执行转字符串、打印操作,大幅精简代码冗余
优化后代码
import time def process_time(current_time): # 注:原代码中一天的秒数有误,标准一天对应的秒数为86400 days = int(current_time // 86400) hours = 24 * ((current_time / 86400) - days) whole_hours = int(hours) minutes = 60 * (hours - whole_hours) whole_minutes = int(minutes) seconds = 60 * (minutes - whole_minutes) whole_seconds = int(seconds) # 仅判断小时对应的展示值和时段,不做重复输出 if whole_hours >= 12: hr = whole_hours - 12 period = "PM" elif 0 < whole_hours < 12: hr = whole_hours period = "AM" else: hr = 12 period = "AM" # 统一格式化输出,:02d表示整数不足2位时自动补前导0 print(f"It is {hr:02d}:{whole_minutes:02d}:{whole_seconds:02d} {period}.") print(f"It has been {days} days since the epoch.") # 测试午夜场景 process_time(86400)
效果说明
格式化语法{变量:02d}会自动将整数值转换为至少2位的字符串,小于10的数值会自动在左侧补0,完全满足分钟、秒位的补零需求。上述测试代码的输出效果如下:
It is 12:00:00 AM. It has been 1 days since the epoch.
内容的提问来源于stack exchange,提问作者emfastic
相关产品推荐
相关产品推荐

