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

Kent Johnson kent37 at tds.net
Thu Dec 9 11:58:52 CET 2004


Liam Clarke wrote:
> Hi Brian and Dick, 
> 
> I for one have learnt a lot from this combined poke around the
> workings of datetime. The datetime.year thing never occurred to me,
> yet it was so obvious when I saw it being used.
> 
> I give you, my python alarm clock timing mechanism, final version!
> 
> http://www.rafb.net/paste/results/qur2Pw95.html

Excuse me for butting in at the last minute, but you can use datetime for the date comparison as 
well. If you create desiredTime first, you can directly compare it with nowTime and increment it if 
necessary. Also note you can give better names to the hour and minute strings by using tuple assignment:

ja=sys.argv[1]
hh, mm=ja.split(':')
nowTime=datetime.datetime.now()
desiredTime=nowTime.replace(hour=int(hh), minute=int(mm),second=0)

if desiredTime <= nowTime:
     desiredTime += datetime.timedelta(days=1)

Kent

> 
> It works on the cmd line - 
> 
> python alarm.py 17:30 
> 
> Sets the alarm for the next occurrence of 17:30, using nothing  but
> datetime.datetime objects, and one timedelta (maybe).
> 
> 'Twas a good discussion. : )
> 
> Liam Clarke
> 
> On Thu, 09 Dec 2004 00:12:04 -0500, Brian van den Broek
> <bvande at po-box.mcgill.ca> wrote:
> 
>>Brian van den Broek said unto the world upon 2004-12-07 23:57:
>>
>>>Dick Moores said unto the world upon 2004-12-07 12:04:
>>>
>>
>><SNIP all of Dick and most of Brian's reply>
>>
>>
>>
>>>The note you reference:
>>>
>>>date2 is moved forward in time if timedelta.days > 0, or backward if
>>>timedelta.days < 0. Afterward date2 - date1 == timedelta.days.
>>>timedelta.seconds and timedelta.microseconds are ignored. OverflowError
>>>is raised if date2.year would be smaller than MINYEAR or larger than
>>>MAXYEAR.
>>>
>>>presupposes you are adding a timedelta to a datetime as in Tim's
>>>suggestion. It makes no promises if you were doing something goofy like
>>>I was. (If that is what you were trying to get me to see, sorry, but I
>>>missed it.)
>>
>>Hey Dick and all,
>>
>>I've taken a look at your code and finally seen what you meant, Dick.
>>You were trusting datetime (along the same lines that Tim suggested to
>>me) and thus weren't facing the problems I'd caused for myself. Sorry
>>for missing your point before. Thanks,
>>
>>Brian vdB
>>
>>
>>>I hope this clarifies things some :-)
>>
>>Ah, irony!
>>
>>
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 
> 


More information about the Tutor mailing list