简体   繁体   中英

Getting time data from user using Python to schedule task 10 mins into the future

Im trying to get Python to check if time given is at least 10 minutes into the future. when entering data, I am always getting back the 'else' clause; The scheduled time must be at least 10 minutes from now
Here is the code im working with so far:

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 = ''

Second part of the script a little(lot) further down:

 ### 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')

Consider using the datetime library: http://docs.python.org/library/datetime.html . You can create a two timedelta objects, one for the current moment and one for the scheduled time. Using a substraction, you can see if the scheduled time is less than 10 minutes away from now.

Eg

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 = ''

There are several problems with this script, the most glaring is that you are not considering hour roll over. For example, if time is 5pm and someone puts in 6pm, clause:

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

will be false since self.mi is 00 and schedMi is 00.

you should use a timedelta object. For instance:

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM