The datetime module provides a timedelta class, which can be used to represent information related to date and time differences. In this recipe, you will create timedelta objects and perform operations on them.
How to do it…
Follow along with these steps to execute this recipe:
- Import the necessary module from the Python standard library:
>>> from datetime import timedelta
- Create a timedelta object with a duration of 5 days. Assign it to td1 and print it:
>>> td1 = timedelta(days=5)
>>> print(f'Time difference: {td1}')
We get the following output:
Time difference: 5 days, 0:00:00
- Create a timedelta object with a duration of 4 days. Assign it to td2 and print it:
>>> td2 = timedelta(days=4)
>>> print(f'Time difference: {td2}')
We get the following output:
Time difference: 4 days, 0:00:00
- Add td1 and td2 and print the output:
>>> print(f'Addition: {td1} + {td2} = {td1 ...