The Python timedelta is a module that represents the time difference between two points in time. module has functions that allow you to calculate the elapsed seconds, minutes, hours, days, and weeks from one point in time to another. It also includes constants for commonly used units like DAYS_PER_YEAR (365), HOURS_PER_DAY (24), and SECONDS_IN_A_MINUTE (60).
In this post, we will explore the Python timedelta object. This object represents time in different units such as days, hours, minutes, and seconds. It is used to add or subtract from a date and to find the difference between two dates.
Table of Contents
How to work with Python timedelta Function?
In Python, the datetime library is present for date manipulations. Python datetime library consists of a timedelta class, which allows easy calculation of time intervals.
We can use this function to add or subtract some time from the date object.
What is Syntax of Python timedelta?
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
- The arguments passed in Python function are optional. They carry default values equals to 0. The data types used in these arguments are integers, float both positive and negative.
- Timedelta function in Python returns Date in output.
If we specify start and end as strings, then the formatted() method of ‘timedelta’ will return a nicely readable string representation.
The timedelta objects are used to store the difference between two datetime instances, typically when measuring time intervals in seconds, minutes, hours, days, or years. The constructor for this class takes two arguments representing the start and end times (in UTC) and an optional keyword argument, ‘precision,’ which specifies how many decimal places should be stored with the result.
Python timedelta Examples
Example Code # 01
This is an example of calculating past and future dates using the timedelta function.
from datetime import datetime, timedelta current_date = datetime.now() date_after_one_year = current_date + timedelta(days=365) print('Current Date:', current_date) print('After One Year Date from Now:', date_after_one_year) date_before_five_days = current_date - timedelta(days=5) print('Date before Five Days from Now:', date_before_five_days)
Example Code # 02
Timedelta object is used to calculate the difference between two dates.
from datetime import datetime, timedelta current_date = datetime.now() print('Current Date:', current_date) next_date = current_date + \ timedelta(days = 4) print ("Next Day:", next_date) print('The Time Difference in Two Days:', next_date - \ current_dat
In this article, we discussed how the timedelta() function is present under the datetime library, which can be used to calculate differences in dates and for date manipulations. It provides one of the easiest ways to perform date manipulations. I hope it helped you learn this Python function properly.