Categories
Python Answers

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

Spread the love

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 create a timedelta object and add that to the time.

For instance, we write

import datetime

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

to create a datetime with

a = datetime.datetime(100, 1, 1, 11, 34 ,59)

Then we add a timedelta object to it to add 3 seconds to the datetime with

b = a + datetime.timedelta(0, 3)

The first argument of timedelta is the number of days to add.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *