首页 > 解决方案 > 我正在制作一个时钟,但我的代码中的分钟没有更新。我怎样才能解决这个问题?

问题描述

我正在尝试制作一个 python 代码来告诉时间作为我的第一个初学者项目之一。我终于能够自己解决连接时遇到的一些问题!(向我求道具)。但是,似乎我放入代码的循环不会将分钟更新为当前时间,而是重复它最初开始的分钟。我的循环错了吗?我在这里做错了什么?

import time
import datetime

now = datetime.datetime.now()


while True:
    if now.hour > 12:
        print(str(now.hour-12) + ":" + str(now.minute,) + ":" + str(now.second) + " PM")
        time.sleep(1)   
    elif (now.hour >= 12):
        print(str(now.hour) + ":" + str(now.minute) + ":" + str(now.second) + " PM")
        time.sleep(1)    
    else:
        print(str(now.hour) + ":" + str(now.minute) + ":" + str(now.second) + " AM")
        time.sleep(1) 

标签: python

解决方案


您已将时间设置在 While 循环之外。相反,将其设置在内部,以便在每个循环中更新。

while True:
    now = datetime.datetime.now()
    if now.hour > 12:
        print(str(now.hour-12) + ":" + str(now.minute,) + ":" + str(now.second) + " PM")       
    elif (now.hour >= 12):
        print(str(now.hour) + ":" + str(now.minute) + ":" + str(now.second) + " PM")  
    else:
        print(str(now.hour) + ":" + str(now.minute) + ":" + str(now.second) + " AM")
    time.sleep(1) 

推荐阅读