Add minutes to the current time in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Photo from Unsplash

Add minutes to the current time in Python #

To add minutes 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 minutes 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 16:33:10.981473 result = now + timedelta(minutes=15) print(result) # 👉️ 2022-06-22 16:48:10.981473 print(result.time()) # 👉️ 16:48:10.981473 print(f'{result:%H:%M:%S}') # 👉️ 16:48:10

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 minutes 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 minutes argument in the example.

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

This wouldn't be possible if we only had the time component. For example, 11:58:20PM + 25 minutes 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 16:46:48.089464 result = now + timedelta(minutes=25) print(result) # 👉️ 2022-06-22 17:11:48.089464 # ✅ only get updated time print(result.time()) # 👉️ 17:11:48.089464

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 16:46:48.089464 result = now + timedelta(minutes=25) print(result) # 👉️ 2022-06-22 17:11:48.089464 print(result.time()) # 👉️ 17:11:48.089464 # 👇️ format as HH:MM:SS print(f'{result:%H:%M:%S}') # 👉️ 17:11:48

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 specific 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.