[Tutor] Could I have used time or datetime modules here?
Liam Clarke
cyresse at gmail.com
Mon Dec 6 01:25:38 CET 2004
Hi Dick,
import datetime
OK = 0
while not OK:
wakeup=raw_input( "enter time in 24 hour format for alarm - in this
format HH:MM:SS")
wakeup=wakeup.split(":")
if len(wakeup) == 3:
if -1 < int(wakeup[0]) < 24 and -1 < int(wakeup[1]) < 60 and
-1 < int(wakeup[2]) < 60:
OK = 1
# Above loops until valid input is received.
secIncre = datetime.timedelta(seconds=1)
workingObj = datetime.datetime.now()
idealTimeObj=datetime.time(int(wakeup[0]),int(wakeup[1]),int(wakeup[2]))
#Inits datetime.time(hours, minutes, seconds)
seconds = 0
while workingObj.time() ! = idealTimeObj:
workingObj += secIncre #Increase workingObj by one second
seconds += 1
print seconds
That should, in theory, give the number of seconds between the current
time, and the desired time.
Of course, if you used a datetime.datetime object, and asked your user
to set the desired date, you could use -
nowDateTime=datetime.datetime.now()
desiredDateTime = datetime.datetime(year, month, day, hours, minutes seconds)
difference = desiredDateTime - nowDateTime
print difference
x days, y hours, q minutes, r seconds.
totalSec = (x*86400)+(y*3600)+(q*60)+r
Of course, getting x, y, q, and r is a bit finicky,
Or, for your purposes -
curDateTime = datetime.datetime.now()
wakeup=raw_input( "enter time in 24 hour format for alarm - in this
format HH:MM:SS")
wakeup=wakeup.split(":")
#Going to assume that valid input was entered
timeinfo=[]
for element in wakeup:
t = int(element)
timeinfo.append(t)
desiredDateTime = curDateTime.replace(t[0], t[1], t[2]) #hours,
minutes, seconds
if curDateTime > = desiredDateTime:
#As both times will be on same day, if desired time is previous to
current date, then make it #time for next day.
dayIncre=datetime.timedelta(days=1)
desiredDateTime += dayIncre
difference = desiredDateTime - curDateTime
#Now do some sort of split of difference, as difference will be in x
days, y hours, m minutes, #s seconds format. As I said, I have no
interpreter so I can't check this out.
So yeah, that's a couple of different ways I'd do it using datetime,
but someone else will no doubt do it better and simpler.
HTH
Liam Clarke
More information about the Tutor
mailing list