用Python time
模块制作互动式时钟与计时器是一个非常实用且有趣的项目。通过这个项目,你可以学习到如何使用Python处理时间相关的操作,以及如何创建简单的用户交互。下面,我们将详细介绍如何使用 time
模块制作10个不同的互动式时钟与计时器。
1. 基本时钟
首先,我们从一个基本的时钟开始。这个时钟会每秒更新一次当前的时间。
import time
def basic_clock():
while True:
current_time = time.strftime("%H:%M:%S", time.localtime()) # 获取当前时间
print(current_time, end="\r") # 打印时间并覆盖上一行
time.sleep(1) # 暂停1秒
basic_clock()
2. 倒计时计时器
接下来,我们制作一个倒计时计时器。用户可以输入倒计时的时间(以秒为单位),计时器会在倒计时结束后打印一条消息。
import time
def countdown_timer(seconds):
while seconds > 0:
mins, secs = divmod(seconds, 60) # 将秒转换为分钟和秒
timer = f'{mins:02d}:{secs:02d}' # 格式化时间为 MM:SS
print(timer, end="\r")
time.sleep(1)
seconds -= 1
print("Time's up!")
countdown_timer(10) # 设置10秒倒计时
3. 计时器
一个简单的计时器,用户可以按下任意键停止计时器并显示经过的时间。
import time
def simple_timer():
input("Press Enter to start the timer")
start_time = time.time() # 记录开始时间
input("Press Enter to stop the timer")
end_time = time.time() # 记录结束时间
elapsed_time = end_time - start_time # 计算经过的时间
print(f"Elapsed time: {elapsed_time:.2f} seconds")
simple_timer()
4. 闹钟
一个简单的闹钟,用户可以设置一个特定的时间,当到达该时间时,程序会发出提示。
import time
def alarm_clock(alarm_time):
while True:
current_time = time.strftime("%H:%M:%S", time.localtime())
if current_time == alarm_time:
print("Alarm! Wake up!")
break
time.sleep(1)
alarm_clock("17:00:00") # 设置闹钟时间为17:00:00
5. 多任务计时器
一个可以同时运行多个计时器的程序。用户可以添加多个计时任务,每个任务完成后会打印一条消息。
import time
import threading
def timer_task(name, duration):
time.sleep(duration)
print(f"{name} task completed after {duration} seconds")
def multi_task_timer():
tasks = [
("Task 1", 5),
("Task 2", 10),
("Task 3", 15)
]
threads = []
for task in tasks:
thread = threading.Thread(target=timer_task, args=task)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
multi_task_timer()
6. 停止计时器
一个可以随时停止的计时器。用户可以输入“stop”来停止计时器并显示经过的时间。
import time
import threading
def stoppable_timer():
start_time = time.time()
stop_event = threading.Event()
def run_timer():
while not stop_event.is_set():
elapsed_time = time.time() - start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds", end="\r")
time.sleep(0.1)
timer_thread = threading.Thread(target=run_timer)
timer_thread.start()
input("Press 'stop' to stop the timer\n")
stop_event.set()
timer_thread.join()
elapsed_time = time.time() - start_time
print(f"\nFinal elapsed time: {elapsed_time:.2f} seconds")
stoppable_timer()
7. 循环计时器
一个可以循环运行的计时器。用户可以设置每次循环的时间间隔和总循环次数。
import time
def loop_timer(interval, loops):
for i in range(loops):
print(f"Loop {i+1}/{loops}")
time.sleep(interval)
print("Timer completed")
loop_timer(2, 5) # 每次循环2秒,共5次
8. 进度条计时器
一个带有进度条的计时器,用户可以看到计时器的进度。
import time
def progress_bar_timer(duration):
for i in range(duration + 1):
progress = i / duration * 100
bar = "#" * int(progress / 2) + "-" * (50 - int(progress / 2))
print(f"\r[{bar}] {progress:.2f}%", end="")
time.sleep(1)
print("\nTimer completed")
progress_bar_timer(10) # 设置10秒计时器
9. 时区转换器
一个可以将本地时间转换为其他时区时间的时钟。
import time
import pytz
from datetime import datetime
def timezone_converter(timezone_str):
local_time = datetime.now(pytz.timezone('UTC'))
target_timezone = pytz.timezone(timezone_str)
target_time = local_time.astimezone(target_timezone)
print(f"Local time: {local_time.strftime('%Y-%m-%d %H:%M:%S %Z')}")
print(f"Target time: {target_time.strftime('%Y-%m-%d %H:%M:%S %Z')}")
timezone_converter('America/New_York') # 转换为纽约时间
10. 实时天气时钟
一个结合了实时天气信息的时钟。用户可以看到当前时间和天气情况。
import time
import requests
def get_weather(api_key, city):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
data = response.json()
weather = data['weather'][0]['description']
temperature = data['main']['temp']
return weather, temperature
def real_time_weather_clock(api_key, city):
while True:
current_time = time.strftime("%H:%M:%S", time.localtime())
weather, temperature = get_weather(api_key, city)
print(f"Time: {current_time}, Weather: {weather}, Temperature: {temperature}°C", end="\r")
time.sleep(10) # 每10秒更新一次
real_time_weather_clock('your_api_key', 'New York') # 替换为你的API密钥和城市
实战案例:制作一个多功能计时器
假设你需要制作一个多功能计时器,用户可以选择不同的模式(基本时钟、倒计时、普通计时器、闹钟等)。我们可以将上述功能整合到一个程序中,让用户通过命令行选择不同的模式。
import time
import threading
import pytz
from datetime import datetime
import requests
def basic_clock():
while True:
current_time = time.strftime("%H:%M:%S", time.localtime())
print(current_time, end="\r")
time.sleep(1)
def countdown_timer(seconds):
while seconds > 0:
mins, secs = divmod(seconds, 60)
timer = f'{mins:02d}:{secs:02d}'
print(timer, end="\r")
time.sleep(1)
seconds -= 1
print("Time's up!")
def simple_timer():
input("Press Enter to start the timer")
start_time = time.time()
input("Press Enter to stop the timer")
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds")
def alarm_clock(alarm_time):
while True:
current_time = time.strftime("%H:%M:%S", time.localtime())
if current_time == alarm_time:
print("Alarm! Wake up!")
break
time.sleep(1)
def multi_task_timer():
tasks = [
("Task 1", 5),
("Task 2", 10),
("Task 3", 15)
]
threads = []
for task in tasks:
thread = threading.Thread(target=timer_task, args=task)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
def timer_task(name, duration):
time.sleep(duration)
print(f"{name} task completed after {duration} seconds")
def stoppable_timer():
start_time = time.time()
stop_event = threading.Event()
def run_timer():
while not stop_event.is_set():
elapsed_time = time.time() - start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds", end="\r")
time.sleep(0.1)
timer_thread = threading.Thread(target=run_timer)
timer_thread.start()
input("Press 'stop' to stop the timer\n")
stop_event.set()
timer_thread.join()
elapsed_time = time.time() - start_time
print(f"\nFinal elapsed time: {elapsed_time:.2f} seconds")
def loop_timer(interval, loops):
for i in range(loops):
print(f"Loop {i+1}/{loops}")
time.sleep(interval)
print("Timer completed")
def progress_bar_timer(duration):
for i in range(duration + 1):
progress = i / duration * 100
bar = "#" * int(progress / 2) + "-" * (50 - int(progress / 2))
print(f"\r[{bar}] {progress:.2f}%", end="")
time.sleep(1)
print("\nTimer completed")
def timezone_converter(timezone_str):
local_time = datetime.now(pytz.timezone('UTC'))
target_timezone = pytz.timezone(timezone_str)
target_time = local_time.astimezone(target_timezone)
print(f"Local time: {local_time.strftime('%Y-%m-%d %H:%M:%S %Z')}")
print(f"Target time: {target_time.strftime('%Y-%m-%d %H:%M:%S %Z')}")
def get_weather(api_key, city):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
data = response.json()
weather = data['weather'][0]['description']
temperature = data['main']['temp']
return weather, temperature
def real_time_weather_clock(api_key, city):
while True:
current_time = time.strftime("%H:%M:%S", time.localtime())
weather, temperature = get_weather(api_key, city)
print(f"Time: {current_time}, Weather: {weather}, Temperature: {temperature}°C", end="\r")
time.sleep(10)
def main():
print("Welcome to the Multi-Function Timer!")
print("1. Basic Clock")
print("2. Countdown Timer")
print("3. Simple Timer")
print("4. Alarm Clock")
print("5. Multi-Task Timer")
print("6. Stoppable Timer")
print("7. Loop Timer")
print("8. Progress Bar Timer")
print("9. Timezone Converter")
print("10. Real-Time Weather Clock")
choice = input("Choose a mode (1-10): ")
if choice == "1":
basic_clock()
elif choice == "2":
seconds = int(input("Enter countdown time in seconds: "))
countdown_timer(seconds)
elif choice == "3":
simple_timer()
elif choice == "4":
alarm_time = input("Enter alarm time (HH:MM:SS): ")
alarm_clock(alarm_time)
elif choice == "5":
multi_task_timer()
elif choice == "6":
stoppable_timer()
elif choice == "7":
interval = int(input("Enter interval in seconds: "))
loops = int(input("Enter number of loops: "))
loop_timer(interval, loops)
elif choice == "8":
duration = int(input("Enter duration in seconds: "))
progress_bar_timer(duration)
elif choice == "9":
timezone_str = input("Enter target timezone (e.g., America/New_York): ")
timezone_converter(timezone_str)
elif choice == "10":
api_key = input("Enter your OpenWeatherMap API key: ")
city = input("Enter city name: ")
real_time_weather_clock(api_key, city)
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
总结
本文介绍了如何使用Python time
模块制作10个不同的互动式时钟与计时器。从基本的时钟到复杂的多任务计时器,再到结合天气信息的实时时钟,每个示例都提供了详细的代码和解释。
好了,今天的分享就到这里了,我们下期见。如果本文对你有帮助,请动动你可爱的小手指点赞、转发、在看吧!
付费合集推荐
文末福利
公众号消息窗口回复“编程资料”,获取Python编程、人工智能、爬虫等100+本精品电子书。