借助datetime和pyttsx3在Python中创建闹钟

使用的模块:

要创建此脚本,我们将使用3个模块:

  • datetime

  • time

  • pyttsx3

datetime模块:datetime是一个内置的python模块,它将帮助我们提供一些处理日期和时间的功能,我们将使用该模块来获取实际的标准时间。

time模块:time是一个内置的python模块,它为我们提供了各种与时间相关的功能,我们正在使用此模块将程序睡眠1秒钟。

pyttsx3:pyttsx3是一个python模块,它将帮助我们将输入文本转换为语音。

我们可以通过两种方式安装:

  • 使用命令:

    pip install pyttsx3
  • Pycharm用户:转到项目解释器并从那里安装此模块

注意:此警报界面基于24小时时钟格式。

我们将如何做到这一点?

我们必须为此接口使用循环。

我们将使用datetime模块获取实际的标准时间。

现在,如果用户时间与标准时间匹配,那么我们必须警告用户,为此,我们将在if条件语句中使用pyttsx3模块,并将在if条件中应用pyttsx3的各种功能。

现在,我们将在脚本中使用的功能是:

  • datetime.datetime.now():这将为我们提供确切的日期和标准时间。

  • datetime.datetime.now().strftime("%H:%M"):在这里,我们仅使用时间,以获取将使用此功能的时间。

  • time.sleep(1):我们必须每秒运行一次循环,这样我们才能停止程序的运行。

关于pyttsx3

当标准时间与用户时间匹配时,我们必须在pyttsx3的帮助下警告用户,我们将使用的功能是:

  • pyttsx3.init():此功能将创建引擎和所有其他功能

  • engine.say():此功能会将文本转换为语音。

  • engine.runAndWait():这将使语音可听。

程序:

# 导入库(日期时间,时间,pyttsx3)
import time,pyttsx3
from datetime import datetime

print("Hello, welcome to my alarming interface...")
print("It is based on 24 hours clock format...")

Name = input("Enter your name: ")

# 打印当前时间 
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time is: ", current_time)

# Enter the time(Hours and minute)
Time=input("Enter the time (HH24:MM): ")

# 开始循环
while True:
    # 通过
    # datetime模块的帮助
    Standard_time=datetime.now().strftime("%H:%M")
    # 休眠程序约1秒钟
    time.sleep(1)
    # 是否有条件检查输入是否 
    # 时间是否匹配
    if Time==Standard_time:
        count=0
        while count<=10:
            count=count+1
            # 为语音模式创建引擎
            engine=pyttsx3.init()
            # 设定声音
            engine.say("Wake up"+Name)            
            engine.runAndWait()
        print("Thankyou For using the Interface")
        break

输出:

Hello, welcome to my alarming interface...
It is based on 24 hours clock format...
Enter your name: Abhinav
Current Time is:  00:33:38
Enter the time (HH24:MM): 00:35

这是我们可以在python中创建Alarming Clock脚本的方法。