Skip to main content
 首页 » 编程设计

python之在 Python 中继续引用当前时间

2025年05月04日13myhome

我想让我的程序在 Python 中引用当前时间。 但是我的程序一直在打印和引用时间戳。我正在使用 Python3.5.3。

import time 
 
timenow = time.strftime("%X") 
 
awake = "06:00:00" # turn on the lights at 6am 
sleep = "22:00:00" # turn off the lights at 10pm 
 
while True: 
    print (timenow) # print the current time 
    if awake <= timenow: 
        print ("Lights On") 
    elif timenow >= sleep: 
        print ("Lights Off") 
 
My current output is... 
 
21:55:46 
Lights On 
21:55:46 
Lights On 
21:55:46 
Lights On 

请您参考如下方法:

这也可能有效。 如果您将时间引用为可以表示为 int 的日期部分。我想在这种情况下比较数字而不是字符串(如您的示例)更好。

import datetime 
 
 
on = 6 
off = 22 
 
 
while True: 
    ctime = datetime.datetime.now() 
    status = 'Lights On' if on < ctime.hour < off else 'Lights Off' 
    print('{}: {}'.format(ctime.strftime('%X'), status))