Adding a day in Python datetimes – use timedelta, not the datetime constructor

If you want “tomorrow” in Python datetimes, don’t construct a datetime like this:

from datetime import datetime, timedelta
td = datetime.today()
tm1 = datetime(td.year, td.month, td.day + 1, 14, 0, 0)
# Don't do this!

Because it will work sometimes, but fail when today is the last day of the month:

Traceback (most recent call last):
  File "./tomorrow", line 6, in 
    tm1 = datetime(td.year, td.month, td.day + 1, 14, 0, 0)
ValueError: day is out of range for month

Instead, use Python’s timedelta, which is designed for this purpose:

from datetime import datetime, timedelta

td = datetime.today()
tm2 = td + timedelta(days=1)

print("tm2=%s" % str(tm2))

And it’s easier to read too.

Leave a Reply

Your email address will not be published. Required fields are marked *