我在比较if语句中的变量时遇到了问题。
我想将变量start_time
与当前时间进行比较,看它是否与当前时间相等,我想将变量start_time
和stop_time
与变量进行比较查看当前程序是否中途或当前程序是否结束的当前时间。
示例:当前时间显示为01:20
,我检查显示为start_date
的变量01:15
。我想检查它是否与当前时间相等并打印the program has started
。当我的当前时间显示为01:35
时,我想查看显示为start_date
的变量01:20
,并且我想检查显示为{stop_date
的变量02:15
{1}}所以我要打印the program is half way through
。如果当前时间大于02:15
,那么我想打印the program has ended
。
以下是我正在使用的内容:
if current_time == start_time:
print "program started"
elif current_time <= stop_time:
print "program finished"
elif current_time > start_time and stop_time < start_time:
print "program half way"
以下是完整代码:
cur = con.cursor()
cur.execute('SELECT start_date, stop_date FROM programs where channel=?', [channels])
stop_date = cur.fetchone()
if stop_date is not None:
start_date = str(stop_date[0])
stop_date = str(stop_date[1])
get_current_time = datetime.datetime.now()
get_start_time = time.strptime(start_date, '%Y%m%d%H%M%S')
start_time = time.strftime('%H:%M', get_start_time)
get_stop_time = time.strptime(stop_date, '%Y%m%d%H%M%S')
stop_time = time.strftime('%H:%M', get_stop_time)
current_time = str(get_current_time)
if current_time == start_time:
print "program started"
elif current_time <= stop_time:
print "program finished"
elif current_time > start_time and stop_time < start_time:
print "program half way"
以下是start_date
数据:
14:18:45 T:4976 NOTICE: 01:15
14:18:45 T:4976 NOTICE: 01:20
14:18:45 T:4976 NOTICE: 00:40
14:18:45 T:4976 NOTICE: 00:10
14:18:46 T:4976 NOTICE: 23:55
14:18:46 T:4976 NOTICE: 01:10
14:18:46 T:4976 NOTICE: 01:50
以下是stop_date
数据:
14:21:12 T:4712 NOTICE: 02:15
14:21:12 T:4712 NOTICE: 03:20
14:21:12 T:4712 NOTICE: 02:30
14:21:12 T:4712 NOTICE: 02:10
14:21:12 T:4712 NOTICE: 01:55
14:21:12 T:4712 NOTICE: 02:05
14:21:12 T:4712 NOTICE: 02:40
这是当前时间: 2016-01-01 14:13:30.707000
当我尝试使用此行elif current_time > start_time and stop_time < start_time
进行比较时,我无法检查当前时间start_date
和stop_date
。
你能否告诉我一个例子,说明如何将变量start_date
和stop_date
与当前时间进行比较以查看程序是否已启动,如果当前程序有结束?
答案 0 :(得分:0)
您不需要将datetime对象转换为字符串,您可以直接比较它们,如下例所示:
from datetime import datetime
start_date = "2016-01-01 14:18:45"
stop_date = "2016-01-01 18:21:12"
current_datetime = datetime.now().replace(microsecond=0)
start_datetime = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
stop_datetime = datetime.strptime(stop_date, '%Y-%m-%d %H:%M:%S')
if current_datetime == start_datetime:
print "program started"
elif start_datetime < current_datetime < stop_datetime:
print "program half way"
else:
print "program finished"