You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 07:22:37