0

我试图让 Python 检查给定的时间是否在未来至少 10 分钟。输入数据时,我总是返回“else”子句;The scheduled time must be at least 10 minutes from now
这是到目前为止我正在使用的代码:

while len(schedTime) == 0:
        schedTime = raw_input('Scheduled Time (hh:mm): ')

        schedHr = schedTime.split(':')[0]
        schedMi = schedTime.split(':')[1]

        try:
            testTime = int(schedHr)
            testTime = int(schedMi)
        except:
            print 'The scheduled time must be in the format hh:mm)'
            schedTime = ''
            continue

        if int(self.hr) <= int(schedHr) and int(self.mi) + 10 <= int(schedMi):
            pass
        else:
            print 'The scheduled time must be at least 10 minutes from now'
            schedTime = ''

脚本的第二部分再往下一点(很多):

 ### Get the current time
    now  = datetime.datetime.now()
    yrF = now.strftime('%Y')
    moF = now.strftime('%m')
    dyF = now.strftime('%d')

    then = now + datetime.timedelta(minutes=10)
    self.hr = then.strftime('%H')
    self.mi = then.strftime('%M')
4

3 回答 3

3

考虑使用日期时间库:http ://docs.python.org/library/datetime.html 。您可以创建两个 timedelta 对象,一个用于当前时刻,一个用于计划时间。使用减法,您可以查看预定时间是否距离现在不到 10 分钟。

例如

t1 = datetime.timedelta(hours=self.hr, minutes=self.mi)
t2 = datetime.timedelta(hours=schedHr, minutes=schedMi)
t3 = t2 - t1
if t3.seconds < 600:
    print 'The scheduled time must be at least 10 minutes from now'
    schedTime = ''
于 2012-09-11T15:02:40.050 回答
0

您应该使用 timedelta 对象。例如:

tdelta = datetime.timedelta(minutes=10)
#read in user_time from command line
current_time = datetime.datetime.now()
if user_time < current_time + tdelta:
    print "Something is wrong here buddy" 
于 2012-09-11T15:16:47.370 回答
0

这个脚本有几个问题,最明显的是你没有考虑小时翻转。例如,如果时间是下午 5 点并且有人在下午 6 点输入,则子句:

int(self.hr) <= int(schedHr) and int(self.mi) + 10 <= int(schedMi)

将是假的,因为 self.mi 是 00 而 schedMi 是 00。

于 2012-09-11T14:54:28.363 回答