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

Tim Peters tim.peters at gmail.com
Tue Dec 7 17:45:55 CET 2004


[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.


More information about the Tutor mailing list