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

Brian van den Broek bvande at po-box.mcgill.ca
Wed Dec 8 05:44:50 CET 2004


Tim Peters said unto the world upon 2004-12-07 11:45:
> [Brian van den Broek]
> ...
> 
>>Or, so I thought. I'd first tried getting the alarm datetime by simply
>>taking the date component of datetime.datetime.now() and adding
>>to the day value. That works fine, provided you are not on the last
>>day of the month. But, when checking boundary cases before
>>posting the code I sent, I discovered this sort of thing:
>>
>>
>>>>>last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity
>>>>>ldj = last_day_of_june                            # short for typing
>>>>>new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
>>
>>Traceback (most recent call last):
>>  File "<pyshell#8>", line 1, in -toplevel-
>>    new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
>>ValueError: day is out of range for month
>>
>>So, adding to the day or the month was out, unless I wanted
>>elaborate code to determine which to add to under what
>>circumstances.
> 
> 
> Actually, you needed simpler code <wink>:
> 
> 
>>>>import datetime
>>>>ldj = datetime.datetime(2004, 6, 30)
>>>>new_day = ldj + datetime.timedelta(days=1)
>>>>print new_day
> 
> 2004-07-01 00:00:00
> 
> or even
> 
> 
>>>>ldy = datetime.datetime(2004, 12, 31)
>>>>new_day = ldy + datetime.timedelta(days=1)
>>>>print new_day
> 
> 2005-01-01 00:00:00
> 
> In other words, if you want to move to the next day, add one day! 
> That always does the right thing.  Subtracting one day moves to the
> previous day, and so on.

Hi Tim and all,

thanks! Since I last posted, I'd found a better way to do what I wanted
than what I'd been using. But it was still clumsy. Your way is of much 
better than any work-aroundish thing.

It does, however, prove my claim up-thread that I'd only skimmed the
datetime docs!

Best to all,

Brian




More information about the Tutor mailing list