python - 我正在制作一个时钟,但我的代码中的分钟没有更新。我怎样才能解决这个问题?
问题描述
我正在尝试制作一个 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)
解决方案
您已将时间设置在 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)
推荐阅读
- c - 在链接静态库时编译 CUDA 代码
- typescript - Angular Highcharts 不呈现 3d 视图(来自 highcharts 包)
- typescript - Typescript :: 条件链接函数
- php - 将日期时间插入url以获取curl php google calendar api
- javascript - 如何从量角器中的输入元素而不是承诺中获取文本值
- google-apps-script - 从公式单元格中获取值以触发电子邮件发送
- c - “ for (int j = 0; j < n || !putchar('\n'); j++) ” 如何工作
- maven - 当排除传递依赖时,maven 究竟做了什么?
- kubernetes - 如何在特定命名空间中创建 K8S 部署?
- android - 在 TextView 中间对齐按钮