0

I've got case when I should add an hour to datetime object and handle situation when such addition leads to day addition. E.g. it is 23:59 1st September, I add 1 hour and got 0:59 2nd September. Standard Python replace function doesn't handle such case and throws ValueError:

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2019, 12, 2, 19, 20, 29, 850677)
>>> dt.replace(hour=dt.hour+10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: hour must be in 0..23

Of course I could write custom function which handles such situation, but I'd like to avoid it.

Could anybody help?

2 Answers 2

3

There we have to use timedelta:

from datetime import datetime, timedelta

dt = datetime.now()
dt2 = dt + timedelta(hours=10)
Sign up to request clarification or add additional context in comments.

Comments

3
dt += datetime.timedelta(hours=10)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.