How to add N seconds to datetime.time in Python?

Sometimes, we want to add N seconds to datetime.time in Python.

In this article, we’ll look at how to add N seconds to datetime.time in Python.

How to add N seconds to datetime.time in Python?

To add N seconds to datetime.time in Python, we can add a timedelta object to a datetime.

For instance, we write:

import datetime

a = datetime.datetime(100, 2, 2, 11, 30, 59)
b = a + datetime.timedelta(0, 3)
print(a.time())
print(b.time())

We create a datetime object with a = datetime.datetime(100, 2, 2, 11, 30, 59).

And then we add 3 seconds with a + datetime.timedelta(0, 3).

We then get the time value in hours:minutes:seconds format with the time method and print the returned result.

Therefore, we have:

11:30:59
11:31:02

from the print output.

Conclusion

To add N seconds to datetime.time in Python, we can add a timedelta object to a datetime.