-- Leo's gemini proxy

-- Connecting to republic.circumlunar.space:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini

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.


Originally posted at 2017-08-07 07:30:38+00:00. Automatically generated from the original post : apologies for the errors introduced.


original post

-- Response ended

-- Page fetched on Sun May 19 03:47:13 2024