[Tutor] Could I have used time or datetime modules here?

Dick Moores rdm at rcblue.com
Sun Dec 5 21:03:10 CET 2004

Thanks, Brian. I looked at your code a long time, and also read the 11/26 
thread you started. I can see how I could use datetime() and your t2 - t1 
to get the seconds for time.sleep(), but  the resulting code I have in 
mind is more convoluted than the heart of my timer3.py, which I quote 
below.  (I don't need the alarm time to be more than 24 hours from 
current time--therefore I want to ignore the year, month, and day.)

import time

alarm = raw_input("Enter alarm time as hhmm: ")

now = time.strftime("%X")  # produces current time in format  hh:mm:ss
nowSecond = int(now[6:])
nowMinute = int(now[3:5])
nowHour = int(now[0:2])

alarmMinute = int(alarm[2:4])
alarmHour = int(alarm[0:2])

hoursDiff = alarmHour - nowHour
minutesDiff = alarmMinute - nowMinute

if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0):
     hoursDiff = hoursDiff + 24 # add a day

sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond

If I'm wrong, could someone please set me right?


Brian van den Broek wrote at 09:54 12/5/2004:
>Dick Moores said unto the world upon 2004-12-05 11:17:
>>I'm wondering if my timer3.py could have been written more simply and 
>>easily by using the time or datetime modules to get the number of 
>>seconds separating the time now and the time to which the alarm is set.
>>IOW, is there an easier way to calculate the time difference between 
>>the time now, say 08:51 and say, tomorrow at 03:45, to take an example 
>>of the most difficult case?
>>See timer3.py at
>>Thanks, tutors.
>>Dick Moores
>>rdm at rcblue.com
>Hi Dick and all,
>as you may recall, it was a week or so ago that I was show how to use 
>datetime, so I'd be cautious about using my suggestion without testing :-)
>But, does this do what is wanted?
><code with Python 2.4>
>import datetime
>def dif_in_seconds(dif):
>     return dif.days * (24 * 60 * 60) + dif.seconds
>t1 = datetime.datetime(2004, 12, 5, 8, 51, 00)
>t2 = datetime.datetime(2004, 12, 6, 15, 45, 00)
>dif = t2 - t1
>seconds_dif = dif_in_seconds(dif)
>print seconds_dif
>with output
> >>>
>I didn't check your link, or read your thread closely, so I don't know 
>if this counts as "easier". But it does look pretty darned easy :-)
>Brian vdB

More information about the Tutor mailing list