Home » datetime.timedelta() Function of Python

datetime.timedelta() Function of Python

by Online Tutorials Library

datetime.timedelta() Function of Python

The ‘timedelta()’ function of Python is present in the datetime library, which is usually used to calculate differences in given dates. We can also use it to manipulate dates in Python, and this function makes it very easy for users to manipulate dates.

Syntax:

For better understanding, we will show how to use the “datetime.timedelta()” function the following example:

Example 1:

In this example, we will print the future dates of three years and three days:

Output:

Initial Date: 2021-10-14 00:09:43.611036  Future Date after Two years: 2023-10-15 00:09:43.611036  Future Date after Two days: 2021-10-17 00:09:43.611036  

Example 2:

In this example, we will see how we can print the past dates of two years and two hours:

Output:

Initial Date: 2021-10-14 00:19:18.449629  Past date before two years: 2019-10-15 00:19:18.449629  Past date before two hours: 2021-10-13 22:19:18.449629  

Example 3:

In this example, we will calculate the difference between the two different dates:

Output:

Initial Date: 2021-10-14 00:31:13.920503  New calculated time:  2021-10-21 06:31:25.975503  Time difference between the given dates is: 7 days, 6:00:12.055000  Time difference between the initial Date and New_time_1 is: 14 days, 16:01:30.215000  

Conclusion

In this tutorial, we learned about the ‘datetime.timedelta()’ function of the datetime library in Python. We have also discussed various examples for better understanding the concept of manipulating dates and calculating the difference between two dates.


Next TopicPython Bio Module

You may also like