以下是一个简单的Python闹钟小程序,它可以设置一个时间,当时间到达时,会在控制台显示一条消息。
代码
import time
from datetime import datetime, timedelta
def set_alarm(alarm_time):
while True:
now = datetime.now()
if now.strftime("%H:%M:%S") == alarm_time:
print("Alarm! The time has arrived!")
break
time.sleep(1)
def main():
alarm_time_str = input("Enter the alarm time (HH:MM:SS): ")
try:
alarm_time = datetime.strptime(alarm_time_str, "%H:%M:%S")
except ValueError:
print("Invalid time format. Please use HH:MM:SS.")
return
# 如果闹钟时间已经过去,设置闹钟为第二天的相同时间
if alarm_time < datetime.now():
alarm_time += timedelta(days=1)
print(f"Alarm is set for {alarm_time.strftime('%Y-%m-%d %H:%M:%S')}")
set_alarm(alarm_time.strftime("%H:%M:%S"))
if __name__ == "__main__":
main()
代码
import time
from datetime import datetime, timedelta
def set_alarm(alarm_time):
while True:
now = datetime.now()
if now.strftime("%H:%M:%S") == alarm_time:
print("Alarm! The time has arrived!")
break
time.sleep(1)
def main():
alarm_time_str = input("Enter the alarm time (HH:MM:SS): ")
try:
alarm_time = datetime.strptime(alarm_time_str, "%H:%M:%S")
except ValueError:
print("Invalid time format. Please use HH:MM:SS.")
return
# 如果闹钟时间已经过去,设置闹钟为第二天的相同时间
if alarm_time < datetime.now():
alarm_time += timedelta(days=1)
print(f"Alarm is set for {alarm_time.strftime('%Y-%m-%d %H:%M:%S')}")
set_alarm(alarm_time.strftime("%H:%M:%S"))
if __name__ == "__main__":
main()
要使用这个程序,用户需要在提示下输入闹钟的时间(格式为HH:MM:SS)。程序会设置一个无限循环,直到当前时间等于闹钟时间,此时会在控制台显示“Alarm! The time has arrived!”的消息。如果用户输入的时间已经过去,程序会自动设置为第二天的同一时间。
例如保存123.py
然后在Python环境下运行它。例如
Python 123.py