Ianis Grigore
Ianis Grigore

Reputation: 23

Adding hours to the current time in Python

I want to add 4 hours to the current hour, only the hour, not minutes. Is that possible? In my program I am using:

hour = current_time.hour

If I just add 4 to the hour, if the time is 22 for example, I will get 26. Can someone help me?

Upvotes: 0

Views: 179

Answers (2)

Jiří Baum
Jiří Baum

Reputation: 6930

If it's a full date-time, you can use the timedelta object:

time_in_four_hours = current_time + timedelta(hours=4)

Upvotes: 1

Gus Beringer
Gus Beringer

Reputation: 341

You might want to read up on the modulo operator.

The code hour = (current_time.hour + 4) % 24 will do exactly what you want.

Upvotes: 1

Related Questions