Python中判断小时更新变量的代码冗余,寻求更简洁实现方式
优化方案
1. 避免重复调用datetime,用临时变量存储当前小时
重复调用datetime.now(TZ).hour不仅冗余,还可能因跨小时导致前后结果不一致(极端场景)。先将当前小时存入临时变量,再执行判断与更新:
current_hour = datetime.now(TZ).hour if thishour != current_hour: thishour = current_hour print("=" * 13) print(f"{current_hour - 12 if current_hour > 12 else current_hour} o'clock") print("-" * 13)
同时用Python的f-string替代字符串拼接,让代码更简洁易读。
2. 用赋值表达式(Python 3.8+)进一步压缩代码
若你的Python版本在3.8及以上,可使用海象运算符:=将变量赋值与判断合并到一行,减少代码行数:
if (current_hour := datetime.now(TZ).hour) != thishour: thishour = current_hour print("=" * 13) print(f"{current_hour - 12 if current_hour > 12 else current_hour} o'clock") print("-" * 13)
3. 封装12小时制转换逻辑(复用场景下)
如果12小时制转换逻辑在代码中多次出现,可将其封装为小函数,提升代码的可维护性:
def to_12h_format(hour): return hour - 12 if hour > 12 else hour current_hour = datetime.now(TZ).hour if thishour != current_hour: thishour = current_hour print("=" * 13) print(f"{to_12h_format(current_hour)} o'clock") print("-" * 13)
内容的提问来源于stack exchange,提问作者israndy
相关产品推荐
相关产品推荐

