Add Seconds to Datetime in Python

Add seconds to datetime in Python

Date and Time in Python

Python provides us with the datetime module that can be used to create datetime objects which can store and manipulate with date and time. This module is equipped with a lot of functionalities to work with such values with ease. We can specify all the attributes of time up to microseconds with this module

Ways to add seconds to datetime object in Python

We will now discuss how to add seconds to datetime in Python.

Using the datetime.timedelta object to add seconds to datetime in Python

We cannot directly add or subtract two datetime objects in Python. For such cases, we use the datetime.timedelta object to represent some difference between two datetime objects.

We can add seconds to datetime in Python using this timedelta class. We will create a timedelta object and specify only its seconds attribute. On adding this to an existing datetime object, we will observe that the seconds have been added up.

See the code below.

Output:

2022-05-09 15:20:20
20

Using the datetime.time.second attribute to add seconds to datetime in Python

As discussed earlier, we can add attributes up to microseconds in the datetime object. We can add the desired seconds while creating the datetime object.

We can specify the attributes for date and time in the datetime constructor. For the date, we have the year, month, and day attributes.

For specifying the time, we have the hour, minute, second, and microsecond attributes.

We will specify the attributes till second to add seconds to datetime in Python.

For example,

Output:

2022-05-09 15:20:15
15

Using the arrow.shift() function to add seconds to arrow object in Python

This method does not add time to a datetime object but rather uses a different module called the arrow. The arrow module also deals with the date and time objects efficiently. It provides an efficient way to work with such values and was built as an improvement to the datetime module with new features.

We can use the shift() function from this module can update a given arrow object. We can update the year, month, day, or any other value using this function.

To add seconds, we use the seconds parameter within the shift() function.

For example,

Output:

2022-02-09T06:19:11.520930+05:30

Conclusion

In this tutorial, we discussed how to add seconds to datetime in Python. We discussed datetime objects and how we can show seconds in this object. We can add seconds to datetime in Python using the datetime.timedelta object. For this, we create a timedelta object containing only seconds. A different module for the same, called arrow, was also demonstrated. The arrow.shift() function can be used to add seconds to an arrow object.

That’s all about how to add seconds to datetime in Python.

Was this post helpful?

Leave a Reply

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