Add hours to the current time in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Photo from Unsplash

Add hours to the current time in Python #

To add hours to the current time in Python:

  1. Use the datetime.now() method to get the current local date and time.
  2. Create a timedelta object by passing the number of hours to the timedelta class.
  3. Sum the current time and the timedelta object.
main.py
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2022-06-22 17:51:46.577659 result = now + timedelta(hours=3) print(result) # 👉️ 2022-06-22 20:51:46.577659 print(result.time()) # 👉️ 20:51:46.577659 print(f'{result:%H:%M:%S}') # 👉️ 20:51:46

Make sure to import the datetime and timedelta classes from the datetime module.

We used the datetime.now method to get the current local date and time.

The now variable stores a datetime object, to which we can add hours using the timedelta class.

The timedelta class can be passed the days, weeks, hours, minutes, seconds, milliseconds and microseconds as arguments.

All of the arguments are optional and default to 0.

It's best to only use keyword arguments in a call to the timedelta class as the order of arguments can be confusing.

We only provided a value for the hours argument in the example.

We need to use a datetime object because it automatically rolls over the days, months and years if necessary.

This wouldn't be possible if we only had the time component. For example, 11:55:30 PM + 2 hours would raise an exception.

If you only need to extract the time after the operation, call the time() method on the datetime object.

main.py
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2022-06-22 17:56:07.569125 result = now + timedelta(hours=5) print(result) # 👉️ 2022-06-22 22:56:07.569125 # ✅ only get updated time print(result.time()) # 👉️ 22:56:07.569125

The datetime.time method returns a time object with the same hour, minute, second and millisecond.

If you need to get the time formatted as HH:MM:SS, use a formatted string literal.

main.py
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2022-06-22 18:02:28.398874 result = now + timedelta(hours=3) print(result) # 👉️ 2022-06-22 21:02:28.398874 print(result.time()) # 👉️ 21:02:28.398874 # 👇️ format as HH:MM:SS print(f'{result:%H:%M:%S}') # 👉️ 21:02:28

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.