Add seconds to the current time in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Check out my new book

Add seconds to the current time in Python #

To add seconds 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 seconds 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 18:23:19.153832 result = now + timedelta(seconds=15) print(result) # 👉️ 2022-06-22 18:23:34.153832 print(result.time()) # 👉️ 18:23:34.153832 print(f'{result:%H:%M:%S}') # 👉️ 18:23:34

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

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

This wouldn't be possible if we only had the time component. For example, 11:59:30 PM + 60 seconds 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 18:26:17.480195 result = now + timedelta(seconds=30) print(result) # 👉️ 2022-06-22 18:26:47.480195 # 👇️ only get updated time print(result.time()) # 👉️ 18:26:47.480195

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:27:15.455150 result = now + timedelta(seconds=10) print(result) # 👉️ 2022-06-22 18:27:25.455150 print(result.time()) # 👉️ 18:27:25.455150 print(f'{result:%H:%M:%S}') # 👉️ 18:27:25

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.